Remove Duplicates from Sorted List
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.
思路:先定义一个结构体指针(ListNode* p);
将head指向的地址赋值给p;
head依旧指向链表的头部;
之后用p对链表进行操作;
返回head;
/**
* 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;
while( p != NULL){
while( p -> next != NULL && p -> val == p -> next -> val){
p -> next = p -> next -> next;
}
p = p -> next;
}
return head;
}
};