19. Remove Nth Node From End of List

来源:互联网 发布:淘宝客服打字慢可以吗 编辑:程序博客网 时间:2024/06/05 15:25

题目:https://leetcode.com/problems/remove-nth-node-from-end-of-list/

代码:

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode removeNthFromEnd(ListNode head, int n) {        ListNode temp = head;        int length = getlength(temp);        if(length==n)        {            head = head.next;            return head;        }        int t = 0;        while(t<n)        {            temp = temp.next;            t++;        }        ListNode cur = head;        while(temp.next!=null)        {            cur = cur.next;            temp = temp.next;        }        cur.next = cur.next.next;        return head;    }    int getlength(ListNode temp){        int length = 1;        while(temp.next!=null)        {            temp = temp.next;            length++;        }        return length;    }}
0 0
原创粉丝点击