码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode][JavaScript]Reverse Linked List

时间:2015-05-30 16:31:55      阅读:287      评论:0      收藏:0      [点我收藏+]

标签:

Reverse Linked List 

Reverse a singly linked list.

click to show more hints.

Hint:

A linked list can be reversed either iteratively or recursively. Could you implement both?

https://leetcode.com/problems/reverse-linked-list/

 

 


 

 

 

反转链表。

 1 /**
 2  * Definition for singly-linked list.
 3  * function ListNode(val) {
 4  *     this.val = val;
 5  *     this.next = null;
 6  * }
 7  */
 8 /**
 9  * @param {ListNode} head
10  * @return {ListNode}
11  */
12 var reverseList = function(head) {
13     if(!head || !head.next){
14         return head;
15     }
16 
17     var res = new ListNode(-1);
18     res.next = head;
19     head = head.next;
20     res.next.next = null;
21     while(head){
22         var tmp = head.next;
23         head.next = res.next;
24         res.next = head;
25         head = tmp;
26     }
27 
28     return res.next;
29 };

 

 

 

[LeetCode][JavaScript]Reverse Linked List

标签:

原文地址:http://www.cnblogs.com/Liok3187/p/4540490.html

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