1. 题目描述
给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 1:
输入: 1->1->2 输出: 1->2
示例 2:
输入: 1->1->2->3->3 输出: 1->2->3
2. 代码实现
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* deleteDuplicates(struct ListNode* head) {
struct ListNode* pre = head;
struct ListNode* cur;
if(!pre)
return;
else
cur = head->next;
while(cur) {
if(pre->val == cur->val)
pre->next = cur->next;
else
pre = pre->next;
cur = cur->next;
}
return head;
}
改进版
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* deleteDuplicates(struct ListNode* head) {
struct ListNode* cur = head;
while(cur && cur->next) {
if(cur->val == cur->next->val)
cur->next = cur->next->next; //删除操作
else
cur = cur->next;
}
return head;
}
3. 收获
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* deleteDuplicates(struct ListNode* head) {
struct ListNode* pre = head;
struct ListNode* cur = head->next;
while(cur) {
if(pre->val == cur->val) {
pre->next = cur->next;
cur = cur->next;
}
else {
pre = pre->next;
cur = cur->next;
}
}
return head;
}
报错: member access within null pointer of type
错误原因:没有判断空指针