list比array更简单, 一次过
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode *deleteDuplicates(ListNode *head) { 12 // Start typing your C/C++ solution below 13 // DO NOT write int main() function 14 ListNode *cur = head; 15 while (cur) { 16 while (cur->next && cur->val == cur->next->val) { 17 cur->next = cur->next->next; 18 } 19 cur = cur->next; 20 } 21 return head; 22 } 23 };
C#
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * public int val; 5 * public ListNode next; 6 * public ListNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 public ListNode DeleteDuplicates(ListNode head) { 11 ListNode cur = head; 12 while (cur != null) { 13 while (cur.next != null && cur.val == cur.next.val) cur.next = cur.next.next; 14 cur = cur.next; 15 } 16 return head; 17 } 18 }