Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given1->1->2 , return 1->2 .
Given1->1->2->3->3 , return 1->2->3 .
<Solution>Given
Given
這題不困難,注意 link list 的操作就好
解題想法如下
- 用兩個指針,prv 和 curr 來檢查數值是否重複
- 重複的話,就把 curr 往後移
- 不重複的話,就把 prv->next 指到 curr
c++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Definition for singly-linked list. | |
* struct ListNode { | |
* int val; | |
* ListNode *next; | |
* ListNode(int x) : val(x), next(NULL) {} | |
* }; | |
*/ | |
class Solution { | |
public: | |
ListNode* deleteDuplicates(ListNode* head) { | |
if(!head) { | |
return NULL; | |
} | |
ListNode *prv = head; | |
ListNode *curr = head->next; | |
while(curr) { | |
if(curr->val > prv->val) { | |
prv->next = curr; | |
prv = curr; | |
} | |
curr = curr->next; | |
} | |
prv->next = curr; | |
return head; | |
} | |
}; |
kotlin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Example: | |
* var li = ListNode(5) | |
* var v = li.`val` | |
* Definition for singly-linked list. | |
* class ListNode(var `val`: Int) { | |
* var next: ListNode? = null | |
* } | |
*/ | |
class Solution { | |
fun deleteDuplicates(head: ListNode?): ListNode? { | |
return if (head == null || head.next == null) { | |
head | |
} else { | |
var prv = head | |
var cur = head.next | |
while(cur != null) { | |
if (cur!!.`val` > prv!!.`val`) { | |
prv.next = cur | |
prv = cur | |
} | |
cur = cur.next | |
} | |
prv!!.next = cur | |
return head | |
} | |
} | |
} |
沒有留言:
張貼留言