Offer 驾到,掘友接招!我正在参与2022春招系列活动-刷题打卡任务,点击查看活动详情。
一、题目描述:
给你单链表的头节点
head,请你反转链表,并返回反转后的链表。 Leetcode:leetcode-cn.com/problems/re…
二、思路分析:
直接头插法。建立头指针h,方便处理。时间复杂度O(n),空间O(1)
三、AC 代码:
* 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 h=new ListNode();
while(head){
let p=head.next;
head.next=h.next;
h.next=head;
head=p;
}
return h.next;
};
四、总结:
简单题,头插就完事了。