[LeetCode] Remove Duplicates from Sorted List 移除有序链表中的重复项
2014-11-01 09:43
495 查看
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given
Given
移除有序链表中的重复项需要定义个指针指向该链表的第一个元素,然后第一个元素和第二个元素比较,如果重复了,则删掉第二个元素,如果不重复,指针指向第二个元素。这样遍历完整个链表,则剩下的元素没有重复项。代码如下:
LeetCode All in One 题目讲解汇总(持续更新中...)
For example,
Given
1->1->2, return
1->2.
Given
1->1->2->3->3, return
1->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) { if (!head || !head->next) return head; ListNode *start = head; while (start && start->next) { if (start->val == start->next->val) { ListNode *tmp = start->next; start->next = start->next->next; delete tmp; } else start = start->next; } return head; } };
LeetCode All in One 题目讲解汇总(持续更新中...)
相关文章推荐
- LeetCode-Remove Duplicates from Sorted List II-从有序链表中移除重复元素-链表操作
- [LeetCode]Merge Two Sorted Lists & Remove Duplicates from Sorted List 两个有序链表合并为一个&删除链表重复元素
- Remove Duplicates from Sorted List(移除有序链表的重复元素)
- 【leetcode 移除有序序列重复数字】Remove Duplicates from Sorted Array(List) I(II)
- Remove Duplicates from Sorted List II 链表移除重复值@LeetCode
- LeetCode 83 Remove Duplicates from Sorted List(从已排序链表中移除重复元素)(*)
- [LeetCode] Remove Duplicates from Sorted List II 移除有序链表中的重复项之二
- LeetCode-Remove Duplicates from Sorted Array-从有序数组移除重复-简单逻辑
- LeetCode | Remove Duplicates from Sorted List(删除链表中重复的数据)
- [leetcode]Remove Duplicates from Sorted List (删除有序节点的值重复的节点 C语言)
- LeetCode 26 Remove Duplicates from Sorted Array (移除有序数组中重复数字)
- Remove Duplicates from Sorted List(去除有序链表中的重复元素)
- Remove Duplicates from Sorted Array II 从有序数组里移除重复出现元素,最多重复出现2次 @LeetCode
- LeetCode(Remove Duplicates from Sorted List) 两道删除排序链表中重复数字
- Remove Duplicates from Sorted List 从链表里移除重复元素 @LeetCode
- LeetCode OJ 之 Remove Duplicates from Sorted List(删除有序链表中重复的数)
- (LeetCode)Remove Duplicates from Sorted List --- 链表中删除重复元素
- leetcode(83)—— 删除已排序链表重复元素(Remove Duplicates from Sorted List)
- Leetcode:Remove Duplicates from Sorted List 删除单链表中重复的节点
- [C++]Remove Duplicates from Sorted List 从已排序的链表中移除重复元素