题目描述
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.
解题思路
本题要求一次遍历,想到的方法是引入一个列表保存每个节点。然后对列表中每个节点进行操作以完成对链表的修改。需要注意的是本题有很多错误校验。
相关知识点
(1)列表中删除元素
自己的代码
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.
解题思路
本题要求一次遍历,想到的方法是引入一个列表保存每个节点。然后对列表中每个节点进行操作以完成对链表的修改。需要注意的是本题有很多错误校验。
相关知识点
(1)列表中删除元素
list.remove(index);//根据下标删除元素
自己的代码
package leetcode;
import java.util.ArrayList;
import java.util.List;
public class RemoveNthNodeFromEndOfList {
public ListNode removeNthFromEnd(ListNode head, int n) {
List<ListNode> list = new ArrayList<ListNode>();
//处理空链表 处理空操作
if(head == null) return null;
if(n <= 0) return null;
while(head != null){
list.add(head);
head = head.next;
}
//处理异常操作
if(n > list.size()) return null;
//如果只有一个元素
if(list.size() == 1) return null;
//如果删除的是尾指针
if(n == 1){
list.get(list.size()-2).next = null;
return list.get(0);
}
//如果删除的是指针头
if(list.size() == n) {
list.remove(0);
return list.get(0);
}
int index = list.size() - 1 - n;
list.get(index).next = list.get(index + 2);
list.remove(index + 1);
return list.get(0);
}
public static void main(String[] args) {
ListNode node1 = new ListNode(1);
ListNode node2 = new ListNode(2);
ListNode node3 = new ListNode(3);
ListNode node4 = new ListNode(4);
ListNode node5 = new ListNode(5);
node1.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = node5;
//int n = 2;
//int n = 5;
int n = 1;
RemoveNthNodeFromEndOfList rnnfeol = new RemoveNthNodeFromEndOfList();
//rnnfeol.removeNthFromEnd(node1, n).print();
//node1.print();
//System.out.println(rnnfeol.removeNthFromEnd(null, n));
//System.out.println(rnnfeol.removeNthFromEnd(node1, 0));
//System.out.println(rnnfeol.removeNthFromEnd(node1, -1));
//System.out.println(rnnfeol.removeNthFromEnd(node1, 6));
//System.out.println(rnnfeol.removeNthFromEnd(node5, 1));
rnnfeol.removeNthFromEnd(node4, 1).print();
}
}