# LeetCode-019-删除链表的倒数第 N 个结点

#### 删除链表的倒数第 N 个结点

###### 解法一：利用栈

``````import java.util.Stack;

public class Solution {
/**
* 方法一：利用栈
* @param n
* @return
*/
public static ListNode removeNthFromEnd(ListNode head, int n) {
return null;
}
Stack<Integer> temp = new Stack<>();
}
Stack<Integer> result = new Stack<>();
int count = 1;
boolean findN = false;
while (!temp.isEmpty()) {
if (count == n) {
temp.pop();
findN = true;
count++;
continue;
}
result.push(temp.pop());
count++;
}
if (!findN) {
return null;
}
ListNode resultNode = new ListNode(-1);
ListNode next = resultNode;
while (!result.isEmpty()) {
next.next = new ListNode(result.pop());
next = next.next;
}
return resultNode.next;
}

public static void main(String[] args) {
ListNode root = new ListNode(1);
root.next = new ListNode(2);
root.next.next = new ListNode(3);
root.next.next.next = new ListNode(4);
root.next.next.next.next = new ListNode(5);
root = removeNthFromEnd(root, 2);
while (root != null) {
System.out.print(root.val + "->");
root = root.next;
}
}
}

class ListNode {
int val;
ListNode next;

ListNode() {
}

ListNode(int val) {
this.val = val;
}

ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}``````

【每日寄语】你今天的努力，是幸运的伏笔，当下的付出，是明日的花开。

1.2k 声望
6.1k 粉丝
0 条评论