刷题笔记:反转单链表(reverse single link)

使用方法:迭代

思路:(基础思路)

定义两个指针:双指针 + 临时指针

规范解法:

class Solution {
    public ListNode reverseList(ListNode head) {
     if(head == null){return null;}
     else{
       ListNode pre = null;
       ListNode cur = head;
       while(cur!= null){
         ListNode temp = cur.next;
         cur.next = pre;
         pre = cur;
         cur = temp;
       }
       return pre;
     }
    }
}

不规范解法

class Solution {
    public ListNode reverseList(ListNode head) {
    if(head == null){return head;}
    else{
      ListNode temp ;
      ListNode  newhead = head;
        head = head.next;
        newhead.next = null;
    while(head != null){
        temp = head;
        head = head.next;
       temp.next = newhead;
       newhead = temp;  
    }
    return newhead;
    }
    }
}

易错点:

cur.next = pre;执行后,cur所在节点指向pre,如果此时用临时指temp记录cur,则temp.next 是指向pre的,所以并不能记住cur节点的下一个节点的位置,导致程序形成闭环,直接崩溃!!!!!!!!

所以:正确的过程是:

先用temp记录cur节点的下一节点的位置 ListNode temp = cur.next;

cur指针反转指向pre                                cur.next = pre;   

将cur节点的位置赋给pre                        pre = cur

最后将temp节点的位置赋给cur             cur = temp;(可以发现,最后两次置换操作根本没使用.next就是因为指针的指向发生了变化)

(改变指针只想谁,对对象的本身做了改变)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值