19. 删除链表的倒数第N个节点——LeetCode

心得:对于链表问题,加头指针可能简化问题

/**
 * 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;
	    }
}

  

猜你喜欢

转载自www.cnblogs.com/pc-m/p/10874871.html