这道题本质上不难,难的是细节处理,容易出错。
第一遍写的代码越改越大,越臃肿,此时,不如推倒重写,果然,第二次一遍过。
Remove Duplicates from Sorted List
My SubmissionsTotal Accepted: 90731 Total Submissions: 255705 Difficulty: Easy
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2
, return 1->2
.
Given 1->1->2->3->3
, return 1->2->3
.
下面是Discuss里面的好代码:只有三行!!!
Java写法
1 public ListNode deleteDuplicates(ListNode head) { 2 if(head == null || head.next == null)return head; 3 head.next = deleteDuplicates(head.next); 4 return head.val == head.next.val ? head.next : head; 5 }
另一个好代码,和我的思想差不多,不过更简洁:
1 public class Solution { 2 public ListNode deleteDuplicates(ListNode head) { 3 if (head == null) return head; 4 5 ListNode cur = head; 6 while(cur.next != null) { 7 if (cur.val == cur.next.val) { 8 cur.next = cur.next.next; 9 } 10 else cur = cur.next; 11 } 12 return head; 13 } 14 }
然后是我自己写的:
C语言
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * struct ListNode *next; 6 * }; 7 */ 8 struct ListNode* deleteDuplicates(struct ListNode* head) { 9 if (head == NULL) 10 return NULL; 11 if (head->next == NULL) 12 return head; 13 14 struct ListNode* p = head; 15 struct ListNode* q = p->next; 16 while(p->next != NULL) { 17 if(p->val == p->next->val) { 18 p->next = p->next->next; 19 } 20 else if(p->next != NULL) 21 p = p->next; 22 } 23 24 return head; 25 }