删除链表的倒数第 N 个结点
给你一个链表,删除链表的倒数第 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) {
ListNode slow = new ListNode(0);
slow.next = head;
ListNode ret = slow;
ListNode fast = head;
while(fast!=null&&n>1){
fast=fast.next;
n--;
}
while(fast.next!=null){
slow = slow.next;
fast = fast.next;
}
slow.next=slow.next.next;
return ret.next;
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)