package com.wsq.leetcode;
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public class RemoveNthFromEnd {
public ListNode removeNthFromEnd(ListNode head, int n) {
int tmpN = n;
ListNode pNode = head;
ListNode ansNode = head;
while(pNode.next != null) {
if(tmpN != 0) {
tmpN--;
}else {
ansNode = ansNode.next;
}
pNode = pNode.next;
}
if(tmpN == 1) {
return head.next;
}else {
ansNode.next = ansNode.next.next;
return head;
}
}
public static void main(String[] args) {
int[] a = {1, 2, 3, 4, 5};
ListNode head = createList(a);
System.out.println("删除元素前:");
show(head);
RemoveNthFromEnd rm = new RemoveNthFromEnd();
ListNode ans = rm.removeNthFromEnd(head, 2);
System.out.println("删除元素后");
show(ans);
}
public static void show(int[] a) {
for(int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
System.out.println();
}
public static void show(ListNode head) {
while(head != null) {
System.out.print(head.val + " ");
head = head.next;
}
System.out.println();
}
public static ListNode createList(int[] a) {
ListNode head = new ListNode(a[0]);
ListNode pNode = head;
for(int i = 1; i < a.length; i++) {
ListNode tNode = new ListNode(a[i]);
pNode.next = tNode;
pNode = pNode.next;
}
return head;
}
}