思路:跟删除排序数组相同元素想法一致,想到的是使用双指针,一个慢指针i,一个快指针j。
首先i指向链表头部,j指向i的下一个元素如果j元素的值等于i元素的值则跳过重复元素j = j.next,否则不用跳过该元素每次内循环结束(跳过相同元素结束)使i.next = j;i=i.next,下一遍外循环又会使j指向i的下一个元素进入内循环进行比较。 /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode deleteDuplicates(ListNode head) { ListNode i = head; while(i!=null){ ListNode j = i.next; while(j != null && j.val == i.val){ j = j.next; } i.next = j; i = i.next; } return head; } }使用一个指针current指向当前元素,比较后一个元素与前一个元素是否相等
相等则使current.next指向后一个元素的后一个元素不等则移动指针:current = current.next /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode deleteDuplicates(ListNode head) { ListNode current = head; while(current != null && current.next !=null){ if(current.val == current.next.val){ current.next = current.next.next; }else{ current = current.next; } } return head; } }