56.删除链表中重复的结点
问题:
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表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
head=ListNode(0)
head.next=pHead
pre=head
last=head.next
while last:
if(last.next!=None and last.next.val==last.val):
while(last.next!=None and last.next.val==last.val):
last=last.next ###last指向重复节点的最后一个节点
last=last.next ### 1,2,3,3,5 让last指向5,pre指向2
pre.next=last
else:
pre=pre.next ### 1,2,5 last指向5,pre指向2
last=last.next
return head.next