标签:
题目 |
Remove Duplicates from Sorted List |
通过率 | 34.4% |
难度 | Easy |
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
.
初步构想:处理的对象是Sorted List,既然是已经排好序的链表,所以需要做的就是逐个比较,先将首元素加入到结果链表,然后遍历整个链表,具有相同取值的元素略过,继续比较,遇到不通过的则添加,需要两个指针,一个search指针进行遍历,一个resultHead进行记录。
java代码:
/** * 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) { ListNode search = null,resultHead = head; if(head==null || head.next==null) return head; while(head.next!=null){ search=head.next; if(head.val==search.val){ if(search.next!=null){ head.next=search.next; }else{ head.next=null; } }else if(head.val!=search.val){ head=head.next; } } return resultHead; } }
leetcode----------Remove Duplicates from Sorted List
标签:
原文地址:http://www.cnblogs.com/pku-min/p/4176952.html