leetcode链表总结

  • Post author:
  • Post category:其他




链表中倒数第k个节点

输入一个链表,输出该链表中倒数第k个节点。为了符合大多数人的习惯,本题从1开始计数,即链表的尾节点是倒数第1个节点。例如,一个链表有6个节点,从头节点开始,它们的值依次是1、2、3、4、5、6。这个链表的倒数第3个节点是值为4的节点。

示例:

给定一个链表: 1->2->3->4->5, 和 k = 2.

返回链表 4->5.

思路:快慢指针

package listNode;

class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
    }
}

public class GetKthFromEnd {

    public ListNode getKthFromEnd(ListNode head, int k) {
        ListNode fast = head;
        while(k > 0){
            fast = fast.next;
            k--;
        }
        ListNode slow = head;
        while(fast != null){
            fast = fast.next;
            slow = slow.next;
        }
        return slow;
    }

    public static void main(String[] args) {

        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);

        int k = 5;
        GetKthFromEnd test = new GetKthFromEnd();
        ListNode res = test.getKthFromEnd(head,k);
        while(res != null){
            System.out.println(res.val + " ");
            res = res.next;
        }
    }
}



从尾到头打印链表

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

示例 1:

输入:head = [1,3,2]
输出:[2,3,1]

思路:

遍历一遍链表,用栈存储,然后再用栈弹出存进数组

package listNode;

import java.util.Stack;

public class ReversePrint {

    public int[] reversePrint(ListNode head){
        Stack<Integer> stack = new Stack<>();

        while(head != null){
            stack.push(head.val);
            head = head.next;
        }

        int[] res = new int[stack.size()];
        for(int i = 0; i < res.length;i++){
            res[i] = stack.pop();
        }
        return res;
    }
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);

        ReversePrint test = new ReversePrint();
        int[] res = test.reversePrint(head);
        for(int i:res){
            System.out.print(i + " ");
        }
    }
}



版权声明:本文为owenfy原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。