题目:
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
.
题意:
给定一个有序单链表,删除单链表中的重复元素,使每个元素只显示一次。
比如:
给定1->1->2
,返回1->2
.
给定1->1->2->3->3
,返回1->2->3
.
算法分析:
方法一:
* 链表变数组
* 数组去重复同题目《Remove Duplicates from Sorted Array 》一样
* 数组变新链表
*貌似有点麻烦~~
代码如下:
public class Solution
{
public ListNode deleteDuplicates(ListNode head)
{
if(head==null) return head;
ListNode newhead= new ListNode(0);
ArrayList<Integer> oriinput=new ArrayList<Integer>();
int newinput[] = null;
int i=0;
while(head!=null)
{
oriinput.add(head.val);
head=head.next;
}
int oriinput2[]=new int[oriinput.size()];
for(i=0;i<oriinput.size();i++)
oriinput2[i]=oriinput.get(i);
newinput=removeDuplicates(oriinput2);
ListNode start =newhead;
for(i=0;i<newinput.length;i++)
{
newhead.next=new ListNode(newinput[i]);
newhead=newhead.next;
}
return start.next;
}
public static int[] removeDuplicates(int[] nums)
{
int startindex = 0;
int endindex = 0;
int i=0;
while(endindex<nums.length)
{
while(endindex<nums.length)
{
if(nums[startindex]==nums[endindex])
endindex++;
else
{
break;
}
}
nums[i]= nums[startindex];
startindex=endindex;
i++;
}
int res[]=new int[i];
for(int ii=0;ii<i;ii++)
res[ii]=nums[ii];
return res;
}
}
方法二:
当出现重复元素时,指针跳跃即可。
别人家的代码:
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null || head.next == null)
return head;
ListNode p = head;
while( p!= null && p.next != null){
if(p.val == p.next.val){
p.next = p.next.next;
}else{
p = p.next;
}
}
return head;
}
}