1.题目:
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given1->1->2, return1->2.
Given1->1->2->3->3, return1->2->3.
思路:这个题目由于之前看过,比较经典的链表去重;所以比较简单
1)定义一个指针指向head
2)判断head的val和head.next.val是否相等,如果相等则删除head.next结点;
代码:一开始想用递归,结果超时了,其实简单的while循环就可以;代码逻辑比较简单
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
/*ListNode cur = head;
while(cur != null){
while(cur.next != null && cur.val == cur.next.val){
cur.next = cur.next.next;
}
cur = cur.next;
}
return head;*/
ListNode p = head;
while(p != null){
while(p.next != null && p.val == p.next.val){
p.next = p.next.next;
}
p = p.next;
}
return head;
}
}
2.题目:
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given1->2->3->3->4->4->5, return1->2->5.
Given1->1->1->2->3, return2->3.
这个题目是上面题目的扩展,已排好序的链表去掉有重复值的结点,用递归解决
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
/*if(head == null || head.next == null)
return head;
ListNode fakehead = new ListNode(0);
fakehead.next = head;
ListNode pre = fakehead;
ListNode cur = fakehead.next;
ListNode post = fakehead.next.next;
boolean flag = false;
while(post != null){
if(post.val == cur.val){
flag = true;
post = post.next;
if(post == null){
pre.next = null;
}
}else{
if(flag){
pre.next = post;
flag = false;
}else{
pre = cur;
}
cur = post;
post = post.next;
}
}
return fakehead.next;*/
if (head == null) return null;
if (head.next != null && head.val == head.next.val) {
while (head.next != null && head.val == head.next.val) {
head = head.next;
}
return deleteDuplicates(head.next);
} else {
head.next = deleteDuplicates(head.next);
}
return head;
}
}
尝试别人优秀的办法,比如不需要用到递归的,如下所示,定义一个cur指针,判断是否和下一个值相等,如果相等则cur = cur.next;此方法时间效率比较高
否则
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode prehead = new ListNode(0);
ListNode pre = prehead;
prehead.next = head;
while(pre.next != null){
ListNode cur = pre.next;
while(cur.next != null && cur.val == cur.next.val)
cur = cur.next;
if (cur!=pre.next)
pre.next=cur.next;
else
pre=pre.next;
}
return prehead.next;
}
}