链表中求倒数第几个元素并打印出来

面试中遇到这个问题,写下给大家分享一下 

package com.qey.learn;

import com.sun.org.apache.xerces.internal.dom.PSVIAttrNSImpl;
import jdk.nashorn.internal.ir.LiteralNode;

/**
 * @ClassName Listed
 * @Description
 * @Author qianxl
 * @Date 2021-03-11 17:12
 * @Version 1.1
 **/

/**
 * 链表分为包含头节点
 * 不包含头节点  两种类型
 */
public class Listed {

    private int data;
    private Listed next;

    public Listed(int data) {
        this.data = data;
    }

    public Listed getNext() {
        return next;
    }

    public void setNext(Listed next) {
        this.next = next;
    }

    public void showListed() {
        Listed temp = this.next;
        if (this == null) {
            System.out.println("数据为空");
        }
        while (temp != null) {
            System.out.println(temp.data);
            temp = temp.next;
        }
    }

    public Listed addList(Listed listed) {
        Listed p = this;
        if (p.next == null) {
            p.next = listed;
            return this;
        }
        Listed temp = p.next;
        while (p != null) {
            temp = p;
            p = p.next;
        }
        temp.setNext(listed);
        return this;

    }

    /**
     * 逻辑思路分析:
     * (1)找到倒数下标p1 比如  倒数2  p1为1 则p2 为2  ;循环 p1=p1.next
     *      则当p2=p2.next  当p2.next==null为最后一个元素时,则p1就是倒数第二元素
     *      Lastposition =1 时则p1 倒数第二个元素  lastPosition -=1;
     * @param lastPosition 倒数位置
     * @return
     */
    public Listed findLastN(  int lastPosition) {
        if(lastPosition<=0){
          System.out.println("下标从1开始");
         return null;
        }
        lastPosition -=1;
        //去除head 根节点
        Listed temp = this.next;
        Listed p1 = this.next;
        //临界条件
         if (p1 == null) {
            return null;
        }

        Listed p2 = p1;
        while (p2 != null&& lastPosition>0) {
            lastPosition--;
            p2 = p2.next;
        }
       

        // 第一种情况就两个节点
        if (p2.next == null) {
            this.next = this.next.next;
        }
        //第二种情况 多个节点
        while (p2 != null) {
      

            if ( p2.next == null) {

                temp.next = temp.next.next;//;
                return this;
            } else {
                temp = p1;
                p1 = p1.next;
                p2 = p2.next;
            }


        }
        return this;
    }


}

class  LinkedlistDemo{
    public static void main(String[] args) {
            Listed head = new Listed(0);

            head.addList(new Listed(2));
            head.addList(new Listed(3));
            head.addList(new Listed(4));
            head.addList(new Listed(5));

            System.out.println(head);
            Listed lastN = head.findLastN(1);
            lastN.showListed();

    }
}

猜你喜欢

转载自blog.csdn.net/JHON07/article/details/114677491