题目描述
给你一个链表,删除链表的倒数第 n
个结点,并且返回链表的头结点。
求解思路
-
先求出链表长度;
- 遍历到被删除的节点,改变前后节点即可。
输入输出示例
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
int len = 0;
ListNode h = head;
while(h != null){
len++;
h = h.next;
}
ListNode dummy = new ListNode(0,head);
ListNode cur = dummy;
for(int i = 0; i < len-n; i++){
cur = cur.next;
}
cur.next = cur.next.next;
return dummy.next;
}
}