您的位置:首页 > 其它

Remove Duplicates from Sorted List

2014-10-28 17:26 232 查看
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.

这是第一道完全在web中写并且提交通过的题目。

跟之前的那道排序数组中消去一样的数字是一个意思。但是用链表操作就容易多了。

忽略掉中间相等的直接拼接到不相等的那个元素过去就ok了。

上代码

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head==null)return head;
int nowValue=head.val;
ListNode nowPoint=head;
ListNode pointer=head;
for(int indexList=0;pointer!=null;pointer=pointer.next){
if(nowPoint.val==pointer.val){
nowPoint.next=pointer.next;
}else{
nowPoint=pointer;
}
}
return head;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  letcode