当前位置:网站首页>[leetcode refers to offer 22. The penultimate node in the linked list (simple)]

[leetcode refers to offer 22. The penultimate node in the linked list (simple)]

2022-04-23 21:21:00 Minaldo7

subject :

Enter a linked list , Output the last number in the list k Nodes . In order to conform to the habits of most people , From 1 Start counting , That is, the tail node of the list is the last 1 Nodes .

for example , A list has 6 Nodes , Start from the beginning , Their values, in turn, are 1、2、3、4、5、6. The last of the list 3 Each node has a value of 4 The node of .

Example :

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

Back to the list 4->5.

source : Power button (LeetCode)
link :https://leetcode-cn.com/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof
Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .

The problem solving process ①:

Double pointer

/** * 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) {
    
        if(head==null)
            return null;
        ListNode first=head,second=head;
        int len=0;
        while(first.next!=null){
    
            len++;
            first = first.next;
        }
        while(len-k+1>0){
    
            second = second.next;
            len--;
        }
        return second;
    }
}

Execution results ①:

 Insert picture description here

The problem solving process ②:

Single pointer

/** * 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) {
    
       if(head==null)
            return null;
        ListNode cur=head;
        while(cur!=null){
    
            cur = cur.next;
            if(k==0)
                head = head.next;
            else
                k--;
        }
        return head;
    }
}

Execution results ②:

 Insert picture description here

版权声明
本文为[Minaldo7]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/111/202204210544479252.html