两种解法:
第一种思路:采用常规方法,判断当前节点的值是否和下一个节点相等,若相等,则让让当前节点的next域为下一个节点的下一个节点;
第二种思路: 采用递归的思想,如下:
//递归处理
private static ListNode deleteDuplicates2(ListNode head){
if (head == null || head.next == null){
return head;
}
head.next = deleteDuplicates2(head.next);
return head.val == head.next.val ? head.next : head;
}
全部代码如下:
public class test29 {
/**
* 删除排序链表中的重复元素: 给定一个已排序的链表的头 head , 删除所有重复的元素,使每个元素只出现一次 。返回已排序的链表 。
*/
static class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
public static void main(String[] args) {
ListNode head = new ListNode();
ListNode p = head;
p.next = new ListNode(1);
p = p.next;
p.next = new ListNode(1);
p = p.next;
p.next = new ListNode(2);
// System.out.println("================");
// while (head.next != null){
// System.out.print(head.next.val);
// if (head.next.next != null){
// head = head.next;
// System.out.print("->");
// }else {
// break;
// }
// }
ListNode deleteDuplicates = deleteDuplicates2(head);
System.out.println("================");
while (deleteDuplicates.next != null){
System.out.print(deleteDuplicates.next.val);
if (deleteDuplicates.next.next != null){
deleteDuplicates = deleteDuplicates.next;
System.out.print("->");
}else {
break;
}
}
}
private static ListNode deleteDuplicates(ListNode head){
ListNode pre = head.next;
ListNode delete = pre.next;
while (delete != null){
if (delete.val == pre.val){
pre.next = delete.next;
// System.out.println("删除元素:"+delete.val);
delete = delete.next;
}else {
pre = pre.next;
delete = delete.next;
}
}
return head;
}
//递归处理
private static ListNode deleteDuplicates2(ListNode head){
if (head == null || head.next == null){
return head;
}
head.next = deleteDuplicates2(head.next);
return head.val == head.next.val ? head.next : head;
}
}
文章评论