83. Remove Duplicates from Sorted List

Given a sorted linked list, delete all duplicates such that each element appear only once.

Example 1:

Input: 1->1->2
Output: 1->2

Example 2:

Input: 1->1->2->3->3
Output: 1->2->3

分析,因为是sorted的list。所以,重复的数字,会是连续的。

只需要比较第一个数字和第二个数字,如果数字相同。那么就踢掉第二个数字。

如果数字不同,则2个数字同时往后移动。

重复比较。

public ListNode DeleteDuplicates(ListNode head)
        {
            ListNode node1 = head;
            ListNode node2 = node1?.next;
            while (node2 != null)
            {
                if (node2.val == node1.val)
                {
                    node1.next = node2.next;
                    node2 = node1.next;
                }
                else
                {
                    node1 = node2;
                    node2 = node2.next;
                }
            }

            return head;
        }
原文地址:https://www.cnblogs.com/chucklu/p/10500384.html