Update 0024.交换链表节点,添加C#版

This commit is contained in:
eeee0717
2023-11-07 09:15:40 +08:00
parent 6316fff080
commit 87a6e78e81

View File

@ -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;
}
```
<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>