链表--删除链表倒数第 n 个结点
2019-12-18 本文已影响0人
暮想sun
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
1->2->3->4->5 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
public static ListNode removeNthFromEnd(ListNode head, int n) {
if (head == null) {
return null;
}
ListNode node = head;
//判断有多少个数据
int k = 0;
List<ListNode> list = new ArrayList<>();
while (node != null) {
k++;
list.add(node);
node = node.next;
}
//正数--需要删除的结点
int removedNum = k + 1 - n;
if (removedNum == k) {
ListNode listNode = list.get(removedNum - 2);
listNode.next = null;
} else {
ListNode listNode = list.get(removedNum - 1);
ListNode node1 = listNode.next;
listNode.next = node1.next;
listNode.val = node1.val;
}
return head;
}
private static class ListNode {
private int val;
private ListNode next;
public ListNode(int val) {
this.val = val;
}
public ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}