remove-duplicates-from-sorted-list

/**
* Given a sorted linked list, delete all duplicates such that each element appear only once.
* For example,
* Given1->1->2, return1->2.
* Given1->1->2->3->3, return1->2->3.
*
* 给定一个已排序的链接列表,删除所有重复项,使每个元素只出现一次。
* 例如,
* 给出1->1->2,返回1->2。
* 给出1->1->2->3->3,返回1->2->3。
*/

/**
 * Given a sorted linked list, delete all duplicates such that each element appear only once.
 * For example,
 * Given1->1->2, return1->2.
 * Given1->1->2->3->3, return1->2->3.
 *
 * 给定一个已排序的链接列表,删除所有重复项,使每个元素只出现一次。
 * 例如,
 * 给出1->1->2,返回1->2。
 * 给出1->1->2->3->3,返回1->2->3。
 */

public class Main38 {
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(1);
//        head.next.next = new ListNode(2);
//        head.next.next.next = new ListNode(3);
        System.out.println(Main38.deleteDuplicates(head).val);
    }

    public static class ListNode {
        int val;
        ListNode next;
        ListNode(int x) {
            val = x;
            next = null;
        }
    }

    public static ListNode deleteDuplicates(ListNode head) {

        ListNode ln = head;
        while (ln != null) {
            while (ln.next != null && ln.val == ln.next.val) {
                ln.next = ln.next.next;
            }
            ln = ln.next;
        }
        return head;
    }
}

  

原文地址:https://www.cnblogs.com/strive-19970713/p/11320272.html