剑指offer-删除链表中重复的结点(python和c++)

题目描述

在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5

非递归的代码思路:

  1. 首先添加一个头节点,以方便碰到第一个,第二个节点就相同的情况

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;
    }
};

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章