82&83 删除排序链表中的重复元素
83. 删除排序链表中的重复元素
给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 1:
输入: 1->1->2
输出: 1->2
输出: 1->2
示例 2:
输入: 1->1->2->3->3
输出: 1->2->3
输出: 1->2->3
思路:将重复节点全部删除完再移动到下一个元素
示例 2:
代码:
/** * 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 *current; current = head; if(current==NULL||current->next==NULL) return head; while(current) { while(current->next&¤t->next->val == current->val)// 将重复节点全部删除完再移动到下一个元素 current->next = current->next->next; current = current->next; } return head; } };
82. 删除排序链表中的重复元素 II
给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中 没有重复出现 的数字。
示例 1:
输入: 1->2->3->3->4->4->5
输出: 1->2->5
输出: 1->2->5
示例 2:
输入: 1->1->1->2->3
输出: 2->3
输出: 2->3
代码:
/** * 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 *pre, *current,*head_res; current = head; if(current==NULL||current->next==NULL) return current; head_res = new ListNode; head_res->next = head; pre = head_res; int del_val; while(current&¤t->next) { if(current->val == current->next->val) { del_val = current->val;//del_val = 3 del_val = 4 while(current&¤t->val==del_val) { pre->next = current->next; //2->3 2->4 2->5 current = current->next; //current = 3 current = 4 current = 5 } } else { pre->next = current;//0->1 1->2 current = current->next;//current = 2 current = 3 pre = pre->next;//pre = 1 pre = 2 } } return head_res->next; delete(head_res); } };
posted on 2020-07-26 21:37 Little-Prince 阅读(101) 评论(0) 编辑 收藏 举报