diff --git a/problems/0024.两两交换链表中的节点.md b/problems/0024.两两交换链表中的节点.md index 36f9b0cc..57034f47 100644 --- a/problems/0024.两两交换链表中的节点.md +++ b/problems/0024.两两交换链表中的节点.md @@ -459,6 +459,40 @@ impl Solution { } ``` +### C# +```C# +// 虚拟头结点 +public ListNode SwapPairs(ListNode head) +{ + var dummyHead = new ListNode(); + dummyHead.next = head; + ListNode cur = dummyHead; + while (cur.next != null && cur.next.next != null) + { + ListNode tmp1 = cur.next; + ListNode tmp2 = cur.next.next.next; + + cur.next = cur.next.next; + cur.next.next = tmp1; + cur.next.next.next = tmp2; + + cur = cur.next.next; + } + return dummyHead.next; +} +``` +``` C# +// 递归 +public ListNode SwapPairs(ListNode head) +{ + if (head == null || head.next == null) return head; + var cur = head.next; + head.next = SwapPairs(head.next.next); + cur.next = head; + return cur; +} +``` +