题意:
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
.
思路:
删除链表中的重复项,考察链表操作。
主要是用循环判断当前节点和下一级节点的值是否相同,是则修改当前节点的 next 指针指向下一节点的 next。
注意操作时要判断指针非空。
代码:
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* root = head;
while(head != NULL)
{
/*下一节点存在,且当前节点和下一节点的值重复*/
while(head->next != NULL && head->val == head->next->val)
{
head->next = head->next->next;
}
head = head->next;
}
return root;
}
};
Python:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param head, a ListNode
# @return a ListNode
def deleteDuplicates(self, head):
p = head
while p != None:
while p.next != None and p.val == p.next.val:
p.next = p.next.next
p = p.next
return head