LeetCode19:
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
//自己的解法class Solution {public ListNode removeNthFromEnd(ListNode head, int n) {if (head == null) {return head;}ListNode tmp = head;int len = 0;while (tmp != null) {tmp = tmp.next;len++;}if (len < n) {return head;}if (len == n) {return head.next;}ListNode tmp1 = head;ListNode tmp2 = head;ListNode tmp3 = head;int num = n - 1;while (num > 0) {tmp3 = tmp3.next;num--;}while (tmp3.next != null){tmp3 = tmp3.next;tmp1 = tmp2;tmp2 = tmp2.next;}tmp1.next = tmp2.next;return head;}}
//优秀解法/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode(int x) { val = x; }* }*/class Solution {public ListNode removeNthFromEnd(ListNode head, int n) {ListNode pre = new ListNode(0);pre.next = head;ListNode start = pre, end = pre;while(n != 0) {start = start.next;n--;}while(start.next != null) {start = start.next;end = end.next;}end.next = end.next.next;return pre.next;}}
