206.反转链表

时游小于 1 分钟LeetCode

206.反转链表

/*
 * @lc app=leetcode.cn id=206 lang=typescript
 *
 * [206] 反转链表
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

function reverseList(head: ListNode | null): ListNode | null {
	if (head == null) return null;

	let beg: ListNode | null = null;
	let mid: ListNode = head,
		end: ListNode | null = head.next;

	while (end != null) {
		mid.next = beg;
		beg = mid;
		mid = end;
		end = end.next;
	}
    // 最后一个节点连接起来
	mid.next = beg;
	return mid;
}

class ListNode {
	val: number;
	next: ListNode | null;
	constructor(val?: number, next?: ListNode | null) {
		this.val = val === undefined ? 0 : val;
		this.next = next === undefined ? null : next;
	}
}

let listTag1 = new ListNode(1);
let listTag2 = new ListNode(2);
let listTag3 = new ListNode(3);
let listTag4 = new ListNode(4);
let listTag5 = new ListNode(5);

listTag1.next = listTag2;
listTag2.next = listTag3;
listTag3.next = listTag4;
listTag4.next = listTag5;
listTag5.next = null;

console.log(reverseList(listTag1));

// @lc code=end

上次编辑于:
贡献者: 15327360835
Loading...