LeetCode19:
给你一个链表,删除链表的倒数第 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) {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;}}
class Solution {public ListNode removeNthFromEnd(ListNode head, int n) {if(head == null){return head;}ListNode newHead = new ListNode(-1);newHead.next = head;ListNode pre = newHead;ListNode post = newHead;int index = 0;while (pre != null){index ++;pre = pre.next;if(index == n){break;}}while (pre!=null && pre.next != null){post = post.next;pre = pre.next;}post.next = post.next.next;return newHead.next;}}
