📅  最后修改于: 2023-12-03 15:07:25.360000             🧑  作者: Mango
在计算机科学中,链表是一种数据结构,由若干个节点组成。每个节点除了储存自身的数据外,还储存指向下一个节点的指针。反转链表是指将原链表中的节点指针方向全部反转,使链表的头变为尾,尾变为头。
在C#中,我们可以使用指针或递归方法来反转链表。以下是两种实现方式:
public class ListNode {
public int val;
public ListNode next;
public ListNode(int val = 0, ListNode next = null) {
this.val = val;
this.next = next;
}
}
public ListNode ReverseList(ListNode head) {
ListNode prev = null;
ListNode cur = head;
while (cur != null) {
ListNode temp = cur.next;
cur.next = prev;
prev = cur;
cur = temp;
}
return prev;
}
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
ListNode reversedList = ReverseList(head);
while (reversedList != null) {
Console.Write(reversedList.val + " ");
reversedList = reversedList.next;
}
// Output: 3 2 1
public ListNode ReverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode reversedList = ReverseList(head.next);
head.next.next = head;
head.next = null;
return reversedList;
}
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
ListNode reversedList = ReverseList(head);
while (reversedList != null) {
Console.Write(reversedList.val + " ");
reversedList = reversedList.next;
}
// Output: 3 2 1
以上是反转链表的两种实现方式,分别使用了指针和递归方法。可以根据自己的需求选择不同的实现方式。