給定一個鏈表,刪除鏈表的倒數第 n 個節點,並且返回鏈表的頭結點。
示例:
給定一個鏈表: 1->2->3->4->5, 和 n = 2.
當刪除了倒數第二個節點後,鏈表變爲 1->2->3->5.
說明:
給定的 n 保證是有效的。
採取暴力法:
/**
* 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) {
if(head==null) return head;
ListNode dum = new ListNode(0);
ListNode cur = dum;
int len=0;
cur.next=head;
while(head!=null)
{
head=head.next;
len++;
}
for(int i=1;i<=len-n;i++) //記得循環次數問題 初始cur在head前一位
cur=cur.next;
cur.next=cur.next.next; //切記不能寫成cur=cur.next.next 只是移動 並沒有指向
return dum.next;
}
}