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指针将重复值的节点去掉就好。写代码时候一定要考虑边界情况,比如head为NULL指针等。
代码如下:
/**
* 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* curr;
curr = head;
while(curr&&curr->next)
{
if(curr->val == curr->next->val)
{
curr->next = curr->next->next;
}
else
{
curr = curr->next;
}
}
return head;
}
};