leetcode82
存在一个按升序排列的链表,给你这个链表的头节点 head ,请你删除链表中所有存在数字重复情况的节点,只保留原始链表中 没有重复出现 的数字。返回同样按升序排列的结果链表。
public class test {
public ListNode deleteDuplicates(ListNode head) {
if(head==null || head.next==null)
return head;
ListNode next=head;
// 当前节点和下一个节点,值不同,则head的值是需要保留的,对head.next继续递归
// if(pre.val!=pre.next.val)
// {
// pre.next=deleteDuplicates(pre.next);
// return pre;
// }
// else {
// //当前相等的话,不能要
// // 一直往下找,找到不重复的节点。返回对不重复节点的递归结果
// ListNode next=pre.next.next;
// while (next!=null && next.val==pre.val){
// next=next.next;
// }
// return deleteDuplicates(next);
// }
if(head.val==next.val){
while(next!=null && next.val==head.val){
next=next.next;
}
head= deleteDuplicates(next);
}
else {
head.next=deleteDuplicates(next);
}
return head;
}
public static ListNode deleteDuplicates2(ListNode head) {
//baseCase
if (head == null || head.next == null) {
return head;
}
ListNode next = head.next;
//如果是这种情况
// 1 --> 1 --> 1 --> 2 --> 3
// head next
//1.则需要移动next直到出现与当前head.val不相等的情况(含null)
//2.并且此时的head已经不能要了,因为已经head是重复的节点
//--------------else-------------
// 1 --> 2 --> 3
// head next
//3.如果没有出现1的情况,则递归返回的节点就作为head的子节点
if (head.val == next.val) {
//1
while (next != null && head.val == next.val) {
next = next.next;
}
//2
head = deleteDuplicates2(next);
} else {
//3
head.next = deleteDuplicates2(next);
}
return head;
}
public static void main(String[] args){
ListNode a1=new ListNode(1);
ListNode a2=new ListNode(2);
ListNode a3=new ListNode(3);
ListNode a4=new ListNode(3);
ListNode a5=new ListNode(4);
ListNode a6=new ListNode(4);
ListNode a7=new ListNode(5);
a1.next=a2;
a2.next=a3;
a3.next=a4;
a4.next=a5;
a5.next=a6;
a6.next=a7;
test M=new test();
ListNode list = M.deleteDuplicates(a1);
while (list.next!=null){
System.out.println(list.val);
list=list.next;
}
}
}