zoukankan      html  css  js  c++  java
  • 剑指:链表中倒数第k个节点

    题目描述

    输入一个链表,输出该链表中倒数第k个结点。

    解法

    pre 指针走 k-1 步。之后 cur 指针指向 phead,然后两个指针同时走,直至 pre 指针到达尾结点。

    即cur与pre始终相距k-1

    当用一个指针遍历链表不能解决问题的时候,可以尝试用两个指针来遍历链表。可以让其中一个指针遍历的速度快一些。

    此题需要考虑一些特殊情况。比如 k 的值小于 0 或者大于链表长度。

    package demo;
    
    public class Solution {
        
        public static class ListNode{
            int val;
            ListNode next = null;
            
            ListNode(int val){
                this.val = val;
            }
        }
        
        public static ListNode findKthtoTail(ListNode head, int k){
            if(head == null || k<1){
                return null;
            }
            ListNode pre = head;
            for(int i=0; i<k-1;i++){//先将pre指针移到第k-1位
                if(pre.next != null)
                    pre = pre.next;
                else
                    return null;
            }
            
            ListNode cur = head;
            while(pre.next != null){//遍历
                pre = pre.next;
                cur = cur.next;
            }
            return cur;
        }
    
        public static void main(String[] args) {
            ListNode head = new ListNode(0);
            
            ListNode node1 = new ListNode(1); head.next = node1;
            ListNode node2 = new ListNode(2); node1.next = node2;
            ListNode node3 = new ListNode(3); node2.next = node3;
            ListNode node4 = new ListNode(4); node3.next = node4;
            ListNode node5 = new ListNode(5); node4.next = node5;
            ListNode node6 = new ListNode(6); node5.next = node6;
            ListNode node7 = new ListNode(7); node6.next = node7;
            ListNode node8 = new ListNode(8); node7.next = node8;
            ListNode node9 = new ListNode(9); node8.next = node9;
            ListNode node10 = new ListNode(10); node9.next = node10;
            
            ListNode cur = head;
            while(cur.next != null){
                cur = cur.next;
                System.out.print(cur.val + " ");
            }
            
            int k = 4;
            ListNode resNode = findKthtoTail(head, k);
            System.out.println("
    链表倒数第"+k+"个元素为:" + resNode.val);
    
        }
    }

    只要从头走n-k+1步即可。

  • 相关阅读:
    mfc窗口,父窗口parentwindow,所有者窗口ownerwindow 区别
    svn冲突问题详解 SVN版本冲突解决详解
    input的on(‘input’,function(0{})事件
    input 输入框两种改变事件的方式
    JSON格式
    AJAX的dataType问题
    什么是跨域请求?
    JSON.parse()和JSON.stringify()使用介绍
    .replace(/-/g,"/")的用法
    docker 实践(一)
  • 原文地址:https://www.cnblogs.com/lisen10/p/11104558.html
Copyright © 2011-2022 走看看