题目:
给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 1:
输入: 1->1->2
输出: 1->2
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None or head.next is None:
return head
cur, next = head, head.next
while next:
if next.val != cur.val:
cur = cur.next
else:
cur.next = next.next
next = next.next
return head
解题思路:这里使用的是双指针法,主要看上去比较清晰便于理解
重点解析:
1.cur, next = head, head.next:用cur指代值,用next来代表连接值
2.if next.val != cur.val:
cur = cur.next:经过比较如果这两个值不相同,那么将这个值存在这个链表中。
3.cur.next = next.next:如果这两个值相同的话,就直接向后走一个,这个值不进行保存
4.next = next.next这里是将车厢再往后移一个,通过一个一个检查最后得出总的链表
处理结果:
相比于单指针法,更加清晰便于理解
来源:力扣(LeetCode)