链表创建(C#)
在C#中,链表可以通过自定义节点类实现。每个节点包含数据域和指向下一个节点的引用。
public class ListNode {
public int val;
public ListNode next;
public ListNode(int val=0, ListNode next=null) {
this.val = val;
this.next = next;
}
}
// 创建链表示例
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
三指针反转链表
三指针法通过维护前驱(prev)、当前(curr)和后继(next)三个指针实现链表反转,时间复杂度O(n),空间复杂度O(1)。
public ListNode ReverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode next = curr.next; // 保存后继节点
curr.next = prev; // 反转指针方向
prev = curr; // 前驱指针后移
curr = next; // 当前指针后移
}
return prev; // 新头节点
}
关键步骤解析
初始化时prev为null,curr指向头节点。每次迭代中:
- 临时保存
curr.next避免断链 - 将当前节点的
next指向prev - 移动
prev和curr指针到下一位置
边界情况处理
- 空链表:直接返回null
- 单节点链表:循环一次后返回原头节点
- 多节点链表:完整遍历直至
curr为null
可视化过程
原始链表:1 -> 2 -> 3 -> null
反转过程:
- prev=null, curr=1, next=2 → 1.next=null
- prev=1, curr=2, next=3 → 2.next=1
- prev=2, curr=3, next=null → 3.next=2 最终得到:3 -> 2 -> 1 -> null
using System;
public class ListNode {
public int Value;
public ListNode Next;
public ListNode(int value) {
Value = value;
Next = null;
}
}
public class LinkedList {
private ListNode head;
// 添加节点到链表尾部
public void Append(int value) {
//创建list的第一遍才会创建head节点,后续head是有值的。
//创建一个Value字段值为value,Next字段为null的head节点,并保存为head(ListNode类)节点
if (head == null) {
head = new ListNode(value);
return;
}
//head节点赋给current节点,如果当前current.Next字段不为空则往后查找直到为空,目的是为了找到list的末尾;
//创建新的末尾节点,并且传入值赋予该节点
ListNode current = head;
while (current.Next != null) {
current = current.Next;
}
current.Next = new ListNode(value);
//注意:一轮走下来,current的位置应该是倒数第二个节点,head节点始终为第一个节点不移动。
}
// 反转链表
public void Reverse() {
ListNode previous = null;
ListNode current = head;
ListNode nextNode = null;
while (current != null) {
nextNode = current.Next; // 暂存下一个节点
current.Next = previous; // 反转当前节点指针
previous = current; // 将previous移动到当前节点
current = nextNode; // 移动到下一个节点
}
head = previous; // 更新头结点
}
// 打印链表
public void PrintList() {
ListNode current = head;
while (current != null) {
Console.Write(current.Value + " ");
current = current.Next;
}
Console.WriteLine();
}
}
class Program {
static void Main(string[] args) {
LinkedList list = new LinkedList();
list.Append(1);
list.Append(2);
list.Append(3);
list.Append(4);
Console.WriteLine("Original List:");
list.PrintList();
list.Reverse();
Console.WriteLine("Reversed List:");
list.PrintList();
}
}
复杂度对比
| 方法 | 时间复杂度 | 空间复杂度 |
|---|---|---|
| 三指针迭代法 | O(n) | O(1) |
| 递归法 | O(n) | O(n) |
| 栈辅助法 | O(n) | O(n) |
5530

被折叠的 条评论
为什么被折叠?



