题解 | #反转链表#

反转链表

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

反转链表的话,如果不考虑用栈,则需要一个辅助结点newHead,但是该节点不存储数据,把原链表结点按照前插法插入,这样链表就倒叙插入了,即完成了反转,最后返回辅助结点的next即可。 public class Solution { public ListNode ReverseList(ListNode head) { if(head==null){

        return null;
    }
   
    ListNode cur=head;                          //指向待插入结点
    ListNode reverseHead=new ListNode(0);      //创建辅助结点
    ListNode next=null;                        //保存待插入结点的下一个结点
   
    while(cur!=null)
    {
        next=cur.next;
        cur.next=reverseHead.next;        //把辅助头结点的next赋值给插入结点的next属性
        reverseHead.next=cur;            //辅助头结点next指向插入结点
        cur=next;                        //待插入结点变为下一个节点
         
    }
    head=reverseHead.next;
   
  
   
   return head;

}

}

全部评论

相关推荐

脑袋锈住了:你这算啥,哥们中科院中强所硕士,本科211,叫我去干分拣,时薪20
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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