题目
- 给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点
解答
public 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;
}
}
private static ListNode removeNthFromEnd(ListNode node, int k) {
if (node == null || k == 0) return null;
// 获取链表长度
int length = getNodeLength(node);
System.out.println("length=== "+length);
ListNode pre = new ListNode(0,node);
ListNode cur=pre;
for (int i = 1; i < length - k+1; i++) {
cur = cur.next;
}
// 修改指针
cur.next = cur.next.next;
return pre.next;
}
private static int getNodeLength(ListNode node) {
int length = 0;
while (node != null) {
length++;
node = node.next;
}
return length;
}