leetcode 83 删除排序链表中的重复元素
题目:给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 1:
输入: 1->1->2 输出: 1->2
示例 2:
输入: 1->1->2->3->3 输出: 1->2->3
以下是leetcode代码片段:
/**
* 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){
return head;
}
ListNode front,behind;//定义ListNode类型的快慢指针;
front = head;//两个指针一开始都指向头结点
behind = head;
while(behind != null){
//如果快慢指针所指向的val值相等,慢指针则不动,快指针指向下一个
if(front.val == behind.val){
behind = behind.next;
}
//如果快慢指针所指的val值不同,则将慢指针的next指向快指针所指的位置,并且慢指针改为front.next(移动慢指针front的位置);
else {
front.next = behind;
front = front.next;
behind = behind.next;//快指针则指向下一个;
}
}
front.next = null;
return head;
}
}
注:
对下面代码做出解释:
front.next = null;
如果最后一个元素和倒数第二个元素相等,由于下列代码语句
if(front.val == behind.val){
behind = behind.next;
}
导致最后俩个元素并没有进行去重处理,致使最后结果输出仍有重复元素(结尾两个元素),所以,让 front.next = null; 避免了上述没有去重的现象;
即使结尾两个数据不相等,次语句也不影响结果,也可以适用。
但此语句的添加,导致了需要在开头对传进来的链表为null的情况另作处理,即代码:
if(head == null){
return head;
}
因为如果是空,则语句front.next = null;则报错,原因是null不是结点类型,所以没有next一说,所以也不存在 front.next = null。
下面是IDEA全部代码:
public class deleteDuplicates {
public static void main(String[] args){
ListNode list = new ListNode(1);//new一个ListNode类型的链表结点
list.next = new ListNode(1);//往链表中添加结点
list.next.next = new ListNode(2);
list.next.next.next = new ListNode(4);
list.next.next.next.next = new ListNode(4);
ListNode res = deleteDuplicates(list);//定义listNode类型的res来接收deleteDuplicates()方法的ListNode类型的头结点head;
while (res!=null){//链表必须一个一个寻找输出,不能直接全部返回
System.out.println(res.val);
res = res.next;
}
}
public static ListNode deleteDuplicates(ListNode head) {
if(head == null){
return head;
}
ListNode front,behind;
front = head;
behind = head;
while(behind != null){
if(front.val == behind.val){
behind = behind.next;
}else {
front.next = behind;
front = front.next;
behind = behind.next;
}
}
front.next = null;
return head;
}
}