青铜挑战—手写链表反转(java实现)

初始化链表:

static class Node{
        int val;
        Node next;
        Node(int data){
            this.val = data;
            this.next=null;
        }
    }
    public static Node initLinkList(int[] array){
        Node head = null,cur = null;
        for(int i = 0;i < array.length;i++){
            Node newNode = new Node(array[i]);
            newNode.next=null;
            if(i==0){
                head=newNode;
                cur=newNode;
            }else{
                cur.next=newNode;
                cur=newNode;
            }
        }
        return head;
    }

反转方式一:用虚拟头结点实现反转

    //虚拟头结点法来反转链表
    public static Node reverseList(Node head){
        Node ans=new Node(-1);
        //ans.next=head;
        Node cur=head;
        while(cur!=null){
            Node next=cur.next;
            cur.next=ans.next;
            ans.next=cur;
            cur=next;
        }
        return ans.next;
    }

        方式一存疑:cur结点应该是指向head,还是指向head的下一个结点?

        已解决:cur指向head,第一步中cur的下一个结点是空,注意看图!

方式二:直接操作链表,不用虚拟头结点

    //直接操作链表,不使用虚拟头结点
    public static Node reverseList2(Node head){
        Node prev=null;
        Node curr=head;
        while(curr!=null){
            Node next=curr.next;
            curr.next=prev;
            prev=curr;
            curr=next;
        }
        return prev;
    }

测试主函数:

    public static void main(String[] args) {
        int[] a={1,2,3,4,5};
        Node head1 = initLinkList(a);
        Node newHead = reverseList(head1);
        System.out.println("value of newHead is :"+newHead.val);
        System.out.println("old head value is :"+head1.val);
        Node newHead2 = reverseList2(newHead);
        System.out.println("value of newHead2 is :"+newHead2.val);
        Node newHead3 = reverseList2(newHead2);
        System.out.println("value of newHead3 is :"+newHead3.val);
/*        Node newHead4 = reverseList3(newHead3);
        System.out.println("value of newHead4 is :"+newHead4.val);*/
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值