解题思路:
找到要删除元素的前驱节点,让其前驱节点指向要删除元素的后继节点
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head == null)
return head;
ListNode Dummyhead = new ListNode(2);
ListNode cur = new ListNode(2);
cur.next = head;
Dummyhead = cur;
int num = 0;
//计算链表中一共有多少个节点
while(head != null){
head = head.next;
num++;
}
//走到要删除节点的前驱节点要走的步数
for(int i = 0;i < num - n;i++){
cur = cur.next;
}
cur.next = cur.next.next;
return Dummyhead.next;
}
}