Reverse a singly linked list.
反转链表。
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
用迭代和递归两种方法实现
迭代:
image.png/**
* 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 === null || head.next === null) { // 链表为空或只有一个节点时,不用反转
return head;
}
var p = head.next;
head.next = null; // 让原本的head变为尾节点
var temp; // 临时指针
while (p !== null) {
temp = p.next;
p.next = head;
head = p;
p = temp;
}
return head
};
递归:
var reverseList = function(head) {
if (head === null || head.next === null) {
return head;
}
var new_head = reverseList(head.next); // 反转后的头节点
head.next.next = head; // 将反转后的链表的尾节点与当前节点相连
head.next = null;
return new_head
};
网友评论