码迷,mamicode.com
首页 > 其他好文 > 详细

逆转链表

时间:2018-01-27 13:48:32      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:def   null   div   body   树的操作   color   数据   tno   ram   

每次我都不想接触链表和树的操作

链表结构
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */

这次要求逆转链表结构(javascript)

核心思想是通过先存储链表当前节点的next数据  --------- let tt = tem.next;

使当前的节点的next指向我们设置的新链表(开始为null)---------------tem.next = newhead;

更新新链表 ---------------------newhead = tem;

更新旧链表准备下一次循环 ----------------------tem = tt;

 1  /**
 2  * @param {ListNode} head
 3  * @return {ListNode}
 4  */
 5 var reverseList = function(head) {
 6         if(head === null){
 7             return null;
 8         }
 9         let newhead = null;
10         let tem = head;
11         while (tem != null){
12             let tt = tem.next;
13             tem.next = newhead;
14             newhead = tem;
15             tem = tt;
16         }
17         return newhead;
18 };

 

逆转链表

标签:def   null   div   body   树的操作   color   数据   tno   ram   

原文地址:https://www.cnblogs.com/xueTP/p/8365083.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!