0
点赞
收藏
分享

微信扫一扫

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

沪钢木子 2021-09-28 阅读 60
LeetCode

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

解法一:利用栈
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;
    }
}

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

举报

相关推荐

0 条评论