Problem:
iven 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.
题意是删除链表中每个节点val相等的节点。没什么算法好说,就操作指针就好。
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 *lastNode = head;
ListNode *result = head;
while (head) {
if (head -> val == lastNode -> val) {
lastNode -> next = head -> next;
head = head -> next;
continue;
}
head = head -> next;
lastNode = lastNode -> next;
}
return result;
}
};