19. 刪除鏈表的倒數第N個節點——LeetCode
阿新 • • 發佈:2019-05-16
init mage sin 問題 new color n-1 http bubuko
心得:對於鏈表問題,加頭指針可能簡化問題
/**
* 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 null;
ArrayList<ListNode> list=new ArrayList<>();//存放節點
ListNode tmp=new ListNode(0);//頭指針
ListNode rHead=tmp;
tmp.next=head;
while(tmp!=null)
{
list.add(tmp);
tmp=tmp.next;
}
list.get(list.size()-n-1).next=list.get(list.size()-n).next;
return rHead.next;
}
}
19. 刪除鏈表的倒數第N個節點——LeetCode