【11_83】Remove Duplicates from Sorted List
生活随笔
收集整理的這篇文章主要介紹了
【11_83】Remove Duplicates from Sorted List
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
這道題本質上不難,難的是細節處理,容易出錯。
第一遍寫的代碼越改越大,越臃腫,此時,不如推倒重寫,果然,第二次一遍過。
?
Remove Duplicates from Sorted List
My Submissions Question Total 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 } View Code?
另一個好代碼,和我的思想差不多,不過更簡潔:
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 } View Code?
然后是我自己寫的: 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 }?
轉載于:https://www.cnblogs.com/QingHuan/p/5051388.html
總結
以上是生活随笔為你收集整理的【11_83】Remove Duplicates from Sorted List的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: PHP开发环境配置
- 下一篇: 跨域请求获取Solr json检索结果并