给你一个链表,删除链表的倒数第 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) {
int ans = 0;
ListNode p = head;
while(p!=null){
ans++;
p = p.next;
}
if(ans == 1&&n==1){
head = null;
return head;
}
if(n==ans){
head = head.next;
return head;
}
//System.out.print(ans);
n = ans - n;
int cnt =0;
p = head;
//System.out.print(n);
while(cnt < n-1&&p!=null){
cnt++;
p = p.next;
}
// System.out.print(cnt);
//System.out.print(p.val);
ListNode q = p.next;
p.next = q.next;
return head;
}
}
下面是递归算法:
/**
* 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) {
return removeNode(head,n)==n?head.next:head;
}
public int removeNode(ListNode node,int n) {
if(node.next == null) return 1;
int m = removeNode(node.next, n);
if(m == n)
if(m == 1) node.next = null;
else node.next = node.next.next;
return m+1;
}
}