【剑指offer】链表中第k个结点/反转链表输出新链表的表头

 

package demo2;
class Node {//节点类

    int data;
    Node next=null;

    public Node(int data) {
        this.data = data;
    }
}
package demo2;
public class MyLinkedList {//单链表类
    public Node head=null;

    public void addNode(int d){
        Node newNode=new Node(d);
        if(head==null){
            head=newNode;
            return;
        }
        Node tmp=head;
        while (tmp.next!=null){
            tmp=tmp.next;
        }
        tmp.next=newNode;
    }
    public void printList(){
        Node tmp=head;
        while (tmp!=null){
            System.out.println(tmp.data);
            tmp=tmp.next;
        }
    }
    public int length(){
        int length=0;
        Node tmp=head;
        while(tmp!=null){
            tmp=tmp.next;
            length++;
        }
        return length;
    }
    public Node Find(int k){//查找倒数第K个节点
        if(k<=0||k>this.length())
            return null;
        Node p1=head;
        Node p2=head;
        for(int i=0;i<k-1;i++){
            if(p1.next!=null){
                p1=p1.next;
            }else{
                return null;
            }
        }
        while (p1.next!=null){
            p1=p1.next;
            p2=p2.next;
        }
        return p2;
    }
    public Node Reverse(){//对链表进行反转
        Node pReverseHead=head;
        Node pNode=head;
        Node pPre=null;
        while(pNode!=null){
            Node pNext=pNode.next;
            if(pNext==null){
                pReverseHead=pNode;
            }
            pNode.next=pPre;
            pNode=pNext;
            pPre=pNode;
        }
        return pReverseHead;
    }
}
package demo2;
public class TestMyLinkedList {//测试类
    public static void main(String args[]){
        MyLinkedList list=new MyLinkedList();
        list.addNode(5);
        list.addNode(4);
        list.addNode(3);
        list.addNode(2);
        list.addNode(1);
        list.printList();
        System.out.println("===================");
        System.out.println(list.Find(6).data);//查找倒数第K个结点
        System.out.println("===================");
        System.out.println(list.Reverse().data);//对链表进行反转输出新链表的头结点
    }
}

结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值