链接:
https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/
大意:
给定一个有序链表的头节点head,链表中含值相同的节点。要求去除链表中所有值相同的节点,只留下链表中值唯一的那些节点。例子:
思路:
由于是一个有序链表,所以判断一个节点的值是否重复,可以将当前节点的值与左右两边节点(如果不为null的话)的值进行比较。如果既不等于左节点的值也不等于右节点的值,那么该节点的值就是唯一的,将该节点添加到新链表即可。
代码:
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode h = new ListNode(0), pre = null, cur = head, newHead = h;
while (cur != null) {
ListNode next = cur.next;
// 判断该节点的值是否重复 只需要判断其值和左右两节点的值是否相同即可
if ((pre == null || cur.val != pre.val) && (next == null || cur.val != next.val)) {
h.next = cur;
h = h.next;
}
pre = cur;
cur = next;
h.next = null;
}
return newHead.next;
}
}
结果:
结论:
提交之前,我还是感觉效率应该还可以的。可是.... 有待优化
其它:
又想着改了下,发现还都是1ms(弱...
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode h = new ListNode(0), dtj = head, cur = head.next, newHead = h; // dtj为待添加到新链表的节点 cur为当前遍历到的节点
int count = 1;
while (cur != null) {
if (dtj.val == cur.val) {
count++;
} else {
if (count == 1) {
h.next = dtj;
h = h.next;
h.next = null;
}
dtj = cur;
count = 1;
}
cur = cur.next;
}
if (count == 1)
h.next = dtj;
return newHead.next;
}
}
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode preOld = null, preNew = null, curNew = head, curOld = head;
while (curOld != null) {
ListNode next = curOld.next;
// 判断该节点的值是否重复 只需要判断其值和左右两节点的值是否相同即可
if ((preOld == null || curOld.val != preOld.val) && (next == null || curOld.val != next.val)) { // 唯一值
curNew.val = curOld.val;
preNew = curNew;
curNew = curNew.next;
}
preOld = curOld;
curOld = curOld.next;
}
if (preNew != null)
preNew.next = null;
else
return null;
return head;
}
}