链表反转-青铜挑战

实例:输入head=[ 1,2,3,4,5]

输出:[5,4,3,2,1]

虚拟头结点实现链表反转

思路:建立虚拟头节点 dummy ,遍历要反转的链表head,cur为当前遍历到的链表节点,每次遍历一个节点,首先得到cur的下一个节点temp方便继续遍历(temp = cur.next),然后把cur的后继指针指向dummy的下一个节点(cur.next = dummy.next),再把dummy的后继指针指向cur(dummy.next = cur),最后 cur 赋值为 temp (cur = temp),继续遍历...

   public NodeList reversalByDummy(NodeList head){
        //定义新链表的节点 dummy
        NodeList dummy =new NodeList(0);
        NodeList cur = head;
        //遍历链表
        while (cur != null){
            //下一个节点
            NodeList temp = cur.next;
            cur.next = dummy.next;
            dummy.next=cur;
            cur=temp;
        }
        return dummy.next;
    }

不带虚拟头结点实现链表反转

思路:定义旧链表首节点cur,下一个要调整的旧链表节点temp,新链表的首节点prev;遍历要反转的链表,每遍历一个链节点,先获取此刻节点cur的下一个节点temp(方便下一次遍历),改变cur的后继节点的指针,并调整新旧链表的表头...

public NodeList reversalByNotDummy(NodeList head){
        //定义旧链表首节点cur,下一个要调整的旧链表节点temp,新链表的首节点prev
        NodeList cur = head;
        NodeList prev = null;
        while (cur!=null){
             NodeList temp = cur.next;
             cur.next = prev;
             prev=cur;
             cur=temp;
        }
        return prev;
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值