【leetcode】Remove Duplicates from Sorted List (easy)
2015-01-18 19:55
330 查看
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given
Given
思路:
简单题,没什么好说的。
大神的代码更加简洁, 没有必要新建一个头结点,就用原来的头结点就好。
For example,
Given
1->1->2, return
1->2.
Given
1->1->2->3->3, return
1->2->3.
思路:
简单题,没什么好说的。
class Solution { public: ListNode *deleteDuplicates(ListNode *head) { if(head == NULL) return NULL; ListNode * ans = head; ListNode * anscur = ans; //记录答案链表的最后一个指针 ListNode * cur = head->next; //记录判断的是原链表中的哪一个指针 while(cur != NULL) { if(anscur->val != cur->val) //只有值变化的时候才把指针接到ans链表后面 节省操作 { anscur->next = cur; anscur = anscur->next; } cur = cur->next; } anscur->next = NULL; //防止最后的指针是重复的,给ans结尾 return ans; } };
大神的代码更加简洁, 没有必要新建一个头结点,就用原来的头结点就好。
class Solution { public: ListNode *deleteDuplicates(ListNode *head) { if(NULL == head) return head; ListNode *cur = head, *nxt = head->next; while (nxt) { if (cur->val != nxt->val) cur = cur->next = nxt; else if (!nxt->next) cur->next = nxt->next; nxt = nxt->next; } return head; } };
相关文章推荐
- LeetCode刷题(C++)——Remove Duplicates from Sorted List(Easy)
- LeetCode-Easy刷题(17) Remove Duplicates from Sorted List
- 【Leetcode】【Easy】Remove Duplicates from Sorted List
- leetcode 083 Remove Duplicates from Sorted List(难易度:Easy)
- [Leetcode 83, easy] Remove Duplicates from Sorted List
- [Leetcode] Remove Duplicates from Sorted List II
- [Leetcode] Remove Duplicates from Sorted List II
- LeetCode: Remove Duplicates from Sorted List
- [LeetCode] Remove Duplicates from Sorted List II
- leetcode 38: Remove Duplicates from Sorted List II
- LeetCode_Remove Duplicates from Sorted List II
- [Leetcode] Remove Duplicates from Sorted List
- [LeetCode] Remove Duplicates from Sorted List 解题报告
- LeetCode Online Judge 题目C# 练习 - Remove Duplicates from Sorted List II
- leetcode 38: Remove Duplicates from Sorted List II
- Leetcode: Remove Duplicates from Sorted List
- LeetCode - Remove Duplicates from Sorted List
- [LeetCode] Remove Duplicates from Sorted List II
- [leetcode] Remove Duplicates from Sorted List
- LeetCode_Remove Duplicates from Sorted List