题目:
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
.
解析:
开始因为疏忽出现了两次runtime error情况,对于链表的问题一般就是如下情况
1. NULL->next
2. 指针是NULL,还用指针的val,p = NULL,p->val
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* deleteDuplicates(ListNode* head) { 12 if(head == NULL || head->next == NULL) 13 return head; 14 ListNode *p = head; 15 while(p->next) 16 { 17 if(p->val == p->next->val) 18 p->next = p->next->next; 19 else 20 p = p->next; 21 } 22 return head; 23 } 24 };