[LeetCode79]Remove Duplicates from Sorted List
来源:互联网 发布:linux删除日志文件 编辑:程序博客网 时间:2024/05/16 19:23
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2
, return 1->2
.
Given 1->1->2->3->3
, return 1->2->3
.
Analysis:
The idea is to use two pointer to scan, compare and remove the duplicates from the start to end.
if p1.val == p2.val, p2 = p2.next
else p1.next = p2, p1 = p1.next, p2 = p2.next
c++
ListNode *deleteDuplicates(ListNode *head) { if(head==NULL||head->next==NULL) return head; ListNode *p1 = head; ListNode *p2 = head->next; while(p2!=NULL){ if(p1->val == p2->val){ p2 = p2->next; } else{ p1->next = p2; p2 = p2->next; p1 = p1->next; } } p1->next = p2; return head;}Java
public ListNode deleteDuplicates(ListNode head) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. ListNode n1=head; while(n1 != null && n1.next !=null){ if(n1.val == n1.next.val){ n1.next = n1.next.next; } else n1 = n1.next; } return head; }
0 0
- [LeetCode79]Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List
- Remove duplicates from sorted list
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List
- kindeditor去掉图片空间
- Unity3D研究院之深入理解Unity脚本的执行顺序(六十二)
- 上台阶,硬币问题的算法
- C与PHP速度对比
- 信号量原语机制
- [LeetCode79]Remove Duplicates from Sorted List
- 连号区间数
- 如何清晰地表达一个事物、观点、原理
- 关于Qt数据库类的基本关系
- 异常4: Unable to instantiate Action, AddZhangMuAction, defined for 'AddZhangAction' in namespace ...
- LabVIEW调试常见问题
- 黑马程序员—单例模式的设计
- Spring AOP (上)
- JAVA数字时钟源程序代码