题目描述
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
用例
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
输入:head = [1,2]
输出:[2,1]
输入:head = []
输出:[]
提示:
- 链表中节点的数目范围是 [0, 5000]
- -5000 <= Node.val <= 5000
示例代码
解法1:直接反转法
var reverseList = function(head) {
let prev=null;
let curr=head;
while(curr){
const next=curr.next;
curr.next=prev;
prev=curr;
curr=next;
}
return prev;
};
解法2:定义反转
/**
* 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) {
let ans=null;
for(let x=head;x!=null;x=x.next){
ans=new ListNode(x.val,ans);
}
return ans;
};
解法3: 栈实现:
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function(head) {
let stack=[]
while(head){
stack.push(head);
head=head.next;
}
let rootNode=new ListNode()
let temp=rootNode;
while(stack.length>0){
temp.next=stack.pop();
temp=temp.next;
}
temp.next=null;
return rootNode.next;
};
执行情况:
Tip