【题目】
分别实现两个函数,一个可以删除单链表中倒数第k个节点,另一个可以删除双链表中倒数第k个节点
【代码】
单链表删除
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode cur = head;
while(cur != null){
cur = cur.next;
n --;
}
if(n > 0){
return head;
}else if(n == 0){
return head.next;
}else{
cur = head;
while(++n != 0){
cur = cur.next;
}
cur.next = cur.next.next;
}
return head;
}
}
【代码】
public class DoubleNode {
public DoubleNode last;
public DoubleNode next;
public int value;
public DoubleNode(int value) {
this.value = value;
}
}
private DoubleNode removeLastKthNode(DoubleNode node, int k) {
if (node == null || k < 1) {
return node;
}
DoubleNode cur = node;
while (cur != null) {
cur = cur.next;
k--;
}
if (k > 0) {
return node;
} else if (k == 0) {
node = node.next;
node.last = null;
} else {
cur = node;
while (++k != 0) {
cur = cur.next;
}
DoubleNode nextNode = cur.next.next;
cur.next = nextNode;
if (nextNode != null) {
nextNode.last = cur;
}
}
return node;
}