https://leetcode.com/problems/remove-duplicates-from-sorted-list/#/description
问题描述:
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.
思路解析:
设两个指针,滑动另一个,如果两个相同则一直滑动,如果两个指针所指的元素值不同,则将第一个连接在第二个指针所指向的那个节点。
但是要注意,第一个指针最后一定要指向null,因为有可能后面的元素都是重复的。这样就能将后面重复的元素都去除掉。
代码如下:
/**
* 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 s=new ListNode(0);
ListNode f=new ListNode(0);
s=head;
f=s.next;
while(f!=null)
{
if(s.val!=f.val){
s.next=f;
s=f;
}
f=f.next;
}
s.next=null;
return head;
}
}