leetcode 83. Remove Duplicates from Sorted List
2016-07-25 19:37
393 查看
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given
Given
可以使用一个指针,也可以使用两个指针来完成,以下是两种做法
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null){
return null;
}
ListNode cur = head;
while(cur.next != null){
if(cur.val == cur.next.val){
cur.next = cur.next.next;
}else{
cur = cur.next;
}
}
return head;
}
}
For example,
Given
1->1->2, return
1->2.
Given
1->1->2->3->3, return
1->2->3.
可以使用一个指针,也可以使用两个指针来完成,以下是两种做法
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null){
return null;
}
ListNode cur = head;
while(cur.next != null){
if(cur.val == cur.next.val){
cur.next = cur.next.next;
}else{
cur = cur.next;
}
}
return head;
}
}
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode deleteDuplicates(ListNode head) { if(head == null) return head; ListNode pre = head; ListNode cur = head.next; while(cur != null && pre != null){ if(cur.val == pre.val){ pre.next = cur.next; cur = cur.next; }else{ pre = pre.next; cur = cur.next; } } return head; } }
相关文章推荐
- 经管类科目
- jvm
- Service的是那种模式
- 【转】关于使用Android6.0编译程序时,出现getSlotFromBufferLocked: unknown buffer: 0xac0f8650问题的解释
- Mybatis JdbcType与Oracle、MySql数据类型对应列表
- oracle表空间
- Linux新手训练营--基础篇
- 求Sn=a+aa+aaa+aaaa+aaaaa的前n项之和,其中a是一个数字,例如:例如:n=5,a=2时:计算:2+22+222+2222+22222
- Best Time to Buy and Sell Stock III
- leetcode 83. Remove Duplicates from Sorted List
- pku暑期训练3filp game
- java的序列化和反序列化
- 使用MYSQL命令直接导入导出SQL文件
- 特效1: 鼠标移动到该区域则显示小图标
- java中位运算问题
- JAVA之线程
- [编写高质量iOS代码的52个有效方法](四)接口与API设计(上)
- Lua闭包的详解
- Servlet
- 使用XCode6.0.1将Cocos2d-x3.1工程打包ipa(支持iOS8)