利用双指针翻转链表的链接方向(从前向后)
指针的定义:
let t: listNode | null = null,
cur: listNode | null = head,
pre: listNode | null = null;
翻转的实现:
while (cur !== null) {
//记录链表正向行进位置
t = cur.next;
//反向链接链表
cur.next = pre;
//使pre指针前进
pre = cur;
//使cur指针前进
cur = t;
}
/*
* @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)
* }
* }
*/
//双指针反转链表
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 {
let t: listNode | null = null,
cur: listNode | null = head,
pre: listNode | null = null;
if (head === null) {
return head;
}
while (cur !== null) {
//记录链表正向行进位置
t = cur.next;
//反向链接链表
cur.next = pre;
//使pre指针前进
pre = cur;
//使cur指针前进
cur = t;
}
return pre;
}
// @lc code=end