題目描述
在一個排序的鏈表中,存在重複的結點,請刪除該鏈表中重複的結點,重複的結點不保留,返回鏈表頭指針。 例如,鏈表1->2->3->3->4->4->5 處理後爲 1->2->5
非遞歸的代碼思路:
- 首先添加一個頭節點,以方便碰到第一個,第二個節點就相同的情況
2.設置 pre ,last 指針, pre指針指向當前確定不重複的那個節點,而last指針相當於工作指針,一直往後面搜索。
參考大神的思路而來的代碼。
python
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplication(self, pHead):
# write code here
if (pHead == None or pHead.next == None):
return pHead
Head = ListNode(0)
Head.next = pHead
pre = Head
last = Head.next
while(last != None):
if(last.next!=None and last.val == last.next.val):
while(last.next!=None and last.val == last.next.val):
last = last.next
pre.next = last.next
last = last.next
else:
pre = pre.next
last = last.next
return Head.next
c++
class Solution {
public:
ListNode* deleteDuplication(ListNode* pHead)
{
//if(pHead==NULL)
// return NULL;
ListNode* pPreNode = NULL;
ListNode* pNode = pHead;
while(pNode!=NULL)
{
ListNode* pNext = pNode->next;
bool needDelete = false;
if(pNext!=NULL&&pNext->val==pNode->val)
needDelete = true;
if(!needDelete)
{
pPreNode = pNode;
pNode = pNode->next;
}
else
{
while(pNext!=NULL&&pNext->val==pNode->val)
{
pNext = pNext->next;
}
if(pPreNode==NULL)
pHead = pNext;
else
pPreNode->next = pNext;
pNode = pNext;
}
}
return pHead;
}
};