题解 | #反转链表#

反转链表

http://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode ReverseList(ListNode head) {
        ListNode pHead=null;//记录反转链表头部
        ListNode cur=head;//用于遍历当前链表
        while(cur!=null){
            //使用头插法,依次将遍历的节点插入pHead
            ListNode temp=pHead;//临时记录头插链表
            pHead=cur;//新节点加入头插链表
            cur=cur.next;//移动遍历指针
            pHead.next=temp;//连接old链表
        }
        return pHead;
    }
}

对于样例 {1,2,3}

简单表示原链表:[1]->[2]->[3]-null

初始
pHead=null
cur=[1]

步骤1 cur=[1]
temp=null(pHead)
pHead=1
cur=2
pHead.next=null(temp)
步骤2 cur=[2]
temp=[1]->null
pHead=2
cur=3
pHead.next=[1]->null
步骤3 cur=[3]
temp=[2]->[1]->null
pHead=3
cur=3
pHead.next=[2]->[1]->null
步骤4 cur=null break
pHead=[3]->[2]->[1]->null

全部评论

相关推荐

白火同学:能。我当初应届沟通了1200,收简历50,面试10左右吧,加油投吧
投了多少份简历才上岸
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务