Question
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given1->1->2, return1->2.
Given1->1->2->3->3, return1->2->3.
Solution
判断当前节点和下一个节点是否相等,相等就跳过。
Code
/**
* 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* pNode = head;
while (pNode != NULL) {
if (pNode->next != NULL && pNode->val == pNode->next->val) {
pNode->next = pNode->next->next;
} else
pNode = pNode->next;
}
return head;
}
};