题目:
给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 1:
输入: 1->1->2
输出: 1->2
示例 2:
输入: 1->1->2->3->3
输出: 1->2->3
链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list
思路:
1、用一个guard保持链表的头结点。遍历链表,如果当前节点的下一个节点的值和当前值一样,则将当前节点的next指针指向像一个节点的下一个节点,否则遍历下一个节点
Python代码:
# 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 not head or not head.next:
return head
guard = head
while head.next:
if head.next.val == head.val:
head.next = head.next.next
else:
head = head.next
return guard
C++代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
ListNode* guard = head;
if (!head || !head->next){
return head;
}
while (head->next){
if (head->next->val==head->val){
head->next = head->next->next;
}else{
head = head->next;
}
}
return guard;
}
};