LeetCode-019-刪除連結串列的倒數第 N 個結點
阿新 • • 發佈:2021-06-24
刪除連結串列的倒數第 N 個結點
題目描述:給你一個連結串列,刪除連結串列的倒數第
n
個結點,並且返回連結串列的頭結點。進階:你能嘗試使用一趟掃描實現嗎?
示例說明請見LeetCode官網。
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。
解法一:利用棧
首先遍歷一遍連結串列,將結點的值放進棧temp裡,然後遍歷temp,過濾掉第n個結點,剩下的重新組裝成連結串列result,返回result。
備註:進階的做法可以採用雙指標法
,待優化。
import java.util.Stack; public class Solution { /** * 方法一:利用棧 * @param head * @param n * @return */ public static ListNode removeNthFromEnd(ListNode head, int n) { if (head == null) { return null; } Stack<Integer> temp = new Stack<>(); while (head != null) { temp.push(head.val); head = head.next; } 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; } }
【每日寄語】你今天的努力,是幸運的伏筆,當下的付出,是明日的花開。