LeetCode Remove Nth Node From End of List

来源:互联网 发布:淘宝卖家用什么app聊天 编辑:程序博客网 时间:2024/06/05 20:12

Description:

Given a linked list, remove the nth node from the end of list and return its head.

Solution:

First get the length of the whole list, then we need to take out the (length-n)th one.

We can get the (length-n-1)th node as node tot, then get next node node next. Use the following code to get the next node out:

tot.next=next.next;

next.next=null;

Pay attention to the condition when the length==n.

public class Solution {public ListNode removeNthFromEnd(ListNode head, int n) {int length = length(head);ListNode tot = head;if (n == length) {tot = head.next;head.next = null;head = tot;} else {for (int i = 0; i < length - n - 1; i++)tot = tot.next;ListNode next = tot.next;tot.next = next.next;next.next = null;}return head;}int length(ListNode head) {int length = 0;ListNode tot = head;while (tot != null) {length++;tot = tot.next;}return length;}}


0 0