[leetcode]@python 83. Remove Duplicates from Sorted List
题目链接
https://leetcode.com/problems/remove-duplicates-from-sorted-list/
题目原文
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2
, return 1->2
.
Given 1->1->2->3->3
, return 1->2->3
.
题目大意
删除链表中的重复元素,使每个元素只出现一次
解题思路
定义一个pre 和cur,1.当二者不等的时候pre.next=cur pre=pre.next 2.当相等的时候pre.next=cur.next 3.每步都是cur=cur.next
代码
# 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 == None or head.next == None:
return head
ans = ListNode(0)
ans.next = head
pre = ans.next
cur = ans.next
while cur:
if pre.val != cur.val:
pre.next = cur
pre = pre.next
else:
pre.next = cur.next
cur = cur.next
return ans.next