注意点:
- 删除头节点的处理
- 在双链表中删除最后一个节点指针悬空情况
代码
public static class Node{
public int value;
public Node next;
public Node(int value) {
this.value = value;
}
}
public static class DoubleNode{
public int value;
public DoubleNode next;
public DoubleNode last;
public DoubleNode(int value) {
this.value = value;
}
}
public static Node removeLastkth(Node head,int k) {
if(head == null || k < 1) return null;
Node cur = head;
int size = 0;
while(cur != null) {
cur = cur.next;
size++;
}
if(k == size) {
head = head.next;
return head;
}
cur = head;
int count = size - k;//删除节点的前一个节点
while(--count != 0) {
cur = cur.next;
}
cur.next = cur.next.next;
return head;
}
public static Node removeLastkth2(Node head,int k) {
if(head == null || k < 1) return null;
Node cur = head;
while(cur != null) {
k--;
cur = cur.next;
}
if(k == 0) {
head = head.next;
return head;
}
cur = head;
while(++k != 0) {
cur = cur.next;
}
cur.next = cur.next.next;
return head;
}
public static DoubleNode removeDoubleLastkth(DoubleNode head,int k) {
if(head == null || k < 1) return null;
DoubleNode cur = head;
int size = 0;
while(cur != null) {
cur = cur.next;
size++;
}
if(k == size) {
head = head.next;
head.last = null;
return head;
}
cur = head;
int count = size - k;//删除节点的前一个节点
while(--count != 0) {
cur = cur.next;
}
cur.next = cur.next.next;
//注意指针悬空情况:删除最后一节点的时候 cur.next == null
if(cur.next != null) {
cur.next.last = cur;
}
return head;
}
public static DoubleNode removeDoubleLastkth2(DoubleNode head,int k) {
if(head == null || k < 1) return null;
DoubleNode cur = head;
while(cur != null) {
k--;
cur = cur.next;
}
if(k == 0) {
head = head.next;
head.last = null;
return head;
}
cur = head;
while(++k != 0) {
cur = cur.next;
}
cur.next = cur.next.next;
//注意指针悬空情况:删除最后一节点的时候 cur.next == null
if(cur.next != null) {
cur.next.last = cur;
}
return head;
}
|