给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 1:
输入: 1->1->2
输出: 1->2
示例 2:
输入: 1->1->2->3->3
输出: 1->2->3
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
代码:
public ListNode deleteDuplicates(ListNode head) {
if(head.next == null) return head;
ListNode currentNode = head;
ListNode nextNode = head.next;
while (currentNode.next != null) {
if (currentNode.val != nextNode.val) {
currentNode.next = nextNode;
currentNode = currentNode.next;
}
if (nextNode.next == null) {
currentNode.next = null;
return head;
}
nextNode = nextNode.next;
}
return head;
}
思路:
利用双指针方式。
首先声明currentNode = head,nextCode = head.next;以下简称( currentNode =>C ; nextNode => N)
C => 记录当前没有重复的节点; N => 在最currentNode记录的加持下大胆往前走(只要前方还有路( 不等于null ));
- while循环判断C.next 是否为null
- 第一个if 判断当前C 的值是否和 N 的值
- 如果相等则另 C.next = N ; C = C.next (往前挪一位即:没有重复的最后一个节点位)
- 第二个if判断N.next 是否为空 也就是前面是否没有元素了(当然前提是 C.val == N.val )
- 如果为空则直接返回,不然继续往前走 N = N.next;
- 例:
因为对链表不是很熟悉,所以花了好久的时间才写出来。卡了好久!!太难受了! 还好后面写出来了,写出来一瞬间就舒服了。继续加油!!!