本文主要是介绍LeetCode 题解(160): Remove Duplicates from Sorted List II,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5
, return 1->2->5
.
Given 1->1->1->2->3
, return 2->3
.
继续Dummy头指针大法。用一个qMoved变量记录是否有duplicate。
C++版:
class Solution {
public:ListNode* deleteDuplicates(ListNode* head) {if(head == NULL)return NULL;ListNode* dummy = new ListNode(head->val - 1);dummy->next = head;ListNode* p = dummy;ListNode* q = head;bool qMoved = false;while(q) {if(q->next && q->val == q->next->val) {q = q->next;qMoved = true;} else if(!qMoved) {p = q;q = q->next;} else {p->next = q->next;q = p->next;qMoved = false;}}return dummy->next;}
};
Java版:
public class Solution {public ListNode deleteDuplicates(ListNode head) {if(head == null)return null;ListNode dummy = new ListNode(head.val - 1);dummy.next = head;ListNode p = dummy;ListNode q = head;boolean qMoved = false;while(q != null) {if(q.next != null && q.next.val == q.val) {q = q.next;qMoved = true;} else if(!qMoved) {p = q;q = q.next;} else {p.next = q.next;q = p.next;qMoved = false;}}return dummy.next;}
}
Python版:
class Solution:# @param {ListNode} head# @return {ListNode}def deleteDuplicates(self, head):if head == None:return Nonedummy = ListNode(head.val-1)dummy.next = headp = dummyq = dummy.nextqMove = Falsewhile q!= None:if q.next != None and q.next.val == q.val:q = q.nextqMove = Trueelif qMove == False:p = qq = q.nextelse:p.next = q.nextq = p.nextqMove = Falsereturn dummy.next
这篇关于LeetCode 题解(160): Remove Duplicates from Sorted List II的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!