LeetCode Algorithms #83 <Remove Duplicates from Sorted List>
2016-02-13 02:07
543 查看
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.
思路:
一个指针向后遍历,发现自己的下一个节点的值和当前指向节点的值,就暂停遍历,把下一个节点的下一个节点当做下一个节点。直到找到下一个节点不同时,再继续遍历。
解:
/** * 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) { return nullptr; } ListNode* stepNode = head; while(stepNode->next != nullptr) { if(stepNode->val == stepNode->next->val) { stepNode->next = stepNode->next->next; continue; } stepNode = stepNode->next; } return head; } };
相关文章推荐
- LeetCode Algorithms #191 <Number of 1 Bits>
- INDIGO STUDIO神器!快速创建WEB、移动应用的交互原型工具【转】
- LeetCode Algorithms #13 <Roman to Integer>
- mongoose 文档(六) Middleware
- [LaTeX] box algorithm adjustbox subfigures, textwidth
- [LaTeX] box algorithm adjustbox subfigures, textwidth
- hdoj--1533--Going Home(最小费用流)
- hdoj--1533--Going Home(最小费用流)
- hdu 3635 Dragon Balls 龙珠 带权并查集
- 【HDOJ】4341 Gold miner
- 跟着猫哥学Golang 15 - goroutine
- django signal and contenttypes初探,可用于好友最新动态,新鲜事,消息通知等
- django学习之 pdf报表(表格)生成
- 跟着猫哥学Golang 14 - error
- 跟着猫哥学Golang 13 - 接口 interface
- POJ 1042 Gone Fishing (贪心)(刘汝佳黑书)
- POJ 2195 Going Home(费用流)
- 用Go开发WeChat接口的一个小坑
- django实现快速文件上传
- 蓝桥杯 算法训练 ALGO-3 K好数