2017暑期工程训练day1_leetcode206_Reverse Linked List

来源:互联网 发布:mac的关闭快捷键 编辑:程序博客网 时间:2024/06/05 16:10

LeetCode206.Reverse Linked List

Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?

题目描述

给出一个链表,输出反转链表。代码中给出了链表节点的构造函数
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/

解决方式

在数据结构的学习中,我们学过了怎样反转链表,这应该是一件很容易的事情,主要其实就是在遍历整个链表的时候先记录,再加新链接,最后拆链这样一过程,想通了这个道理之后,使用avascipt实现即可。
实现代码如下:
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function(head) {
if(!head || !head.next){
return head;
}
var pre = head;
var next;
while(head.next)
{
next = head.next.next;
head.next.next = pre;
pre = head.next;
head.next = next;
}
return pre;
};



原创粉丝点击