题目
给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 1:
输入: 1->1->2
输出: 1->2
示例 2:
输入: 1->1->2->3->3
输出: 1->2->3
解决方法
采用快慢双指针法
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null || head.next == null) return head;
ListNode after =head;
ListNode before = head.next;
while(before!=null ) {
if(before.val == after.val) {
before = before.next;
}else{
after.next = before;
after = before;
before = before.next;
}
}
//此处是为了解决最后一位元素也是存在重复的,如【1->2->3->3】
after.next = null;
return head;
}
}