题目描述
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
输入: head = [1,2,3,4,5]
输出: [5,4,3,2,1]
输入: head = [1,2]
输出: [2,1]
思路
有两种方法可以实现反转数组,分别是递归法和双指针法,虽然这两种方法不同,但是实现两种方法的思路是一致的。
我们拿有示例中的链表来举例,如动画所示:(纠正:动画应该是先移动pre,在移动cur)
伪代码
//初始化
pre=null;
cur=head;
temp=null;
//移动指针
while(cur!=null){
temp=cur.next;
cur.next=pre;
pre=cur;
cur=temp;
}
代码
双指针法代码
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function(head) {
var cur=head,prev=null;
while(cur){
//将cur.next 提前存下来
let temp=cur.next;
//反转链表
cur.next=prev;
//移动指针
prev=cur;
cur=temp;
}
return prev;
};
递归法
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function(head) {
var cur=head,prev=null;
return reverse(cur,prev);
};
function reverse(cur,prev){
//判断是否遍历完了链表
if(cur==null){return prev;}
//存下cur.next
let temp=cur.next;
//反转链表
cur.next=prev;
//移动指针
prev=cur;
cur=temp;
//执行递归
return reverse(cur,prev);
}