剑指 Offer II 024. 反转链表

做题记录:
使用迭代的方式反转
构建节点pre=null, cur=head, next=head.next.
先反转第一个节点,直接使当前节点指向pre,然后当前节点指向cur,cur指向next,next节点指向下一个节点。
直到next节点指向null.

初始化状态(两行为一组状态,其中第一行的p/c/n是pre/cur/next的缩写,第二行n是null的缩写)
p  c  n
n  1->2->3
中间态
p  c  n
n<-1 2->3

   p c  n
n<-1 2->3->null

   p  c  n
n<-1<-2 3->null

      p c  n
n<-1<-2 3->null
循环结束后,将cur指向pre
      p  c  n
n<-1<-2<-3  null

最后,直接返回cur即是反转之后的链表。
附上代码:

public ListNode reverseList(ListNode head) {
    if (head==null || head.next==null){
        return head;
    }
    ListNode pre = null;
    ListNode cur = head;
    ListNode next = head.next;
    while (next!=null){
        cur.next = pre;
        pre = cur;
        cur = next;
        next = next.next;
    }
    cur.next = pre;
    return cur;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值