Problem Description:
Given a sorted linked list, delete all duplicates such that each element appear only once.
题目大意:
给定一个已排序的链表,删除所有重复的结点。
Solutions:
遍历整个链表,发现某个结点的下一个结点的值和它一样时,把它的下一个结点指向再后一个结点。
Code in 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* p = head;
if(!head) return head;
while(p&&p->next)
{
if(p->val==p->next->val)
p->next=p->next->next;
else
p=p->next;
}
return head;
}
};
近期评论