[Sword refers to offer.22] The kth node from the bottom in the linked list (Solved by the stack method)

Input a linked list, and output the kth node from the bottom of the linked list. In order to conform to the habits of most people, this question starts counting from 1, that is, the end node of the linked list is the first node from the bottom.

For example: a linked list has 6 nodes, starting from the head node, their values ​​are 1, 2, 3, 4, 5, 6. The third node from the bottom of this linked list is the node with the value 4.

Example:

Given a linked list: 1->2->3->4->5, and k = 2.

Return to the linked list 4->5.

answer:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode getKthFromEnd(ListNode head, int k) {
         Stack<ListNode> s=new Stack<>();
         if(head==null)
         return null;
         while(head!=null){
             s.push(head);
             head=head.next;
            
         }
         Stack<ListNode> s1=new Stack<>();
         
             if(!s.empty()){
             for(int i=0;i<k;i++){
               s1.push(s.peek());
               s.pop();
             }
         }
         return s1.peek();
    }
}

 

Guess you like

Origin blog.csdn.net/qq_44624536/article/details/114883898