Question:
Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.
从前遍历一遍链表,求出链表的长度,并把节点存储在ArrayList数据结构中,直接访问ArrayList中的节点即可。
java中,除了主类型(int,String,float等) 之外的类型的对象,用等号等于引用,只要改变了一边的值,另一边的也会变化。而主类型的对象用等号是直接赋值。
java代码如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
List<ListNode> nodes = new ArrayList();
ListNode cur = head;
int len = 0;
while(cur != null){
nodes.add(cur);
cur = cur.next;
len ++;
}
if(len - n == 0){
return head.next;
}
ListNode prev = nodes.get(len - n - 1);
if(len - n + 1 >= len){
prev.next = null;
return head;
}
ListNode next = nodes.get(len - n + 1);
prev.next = next;
return head;
}
}