mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
Update 0024.交换链表节点,添加C#版
This commit is contained in:
@ -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">
|
<p align="center">
|
||||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||||
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
||||||
|
Reference in New Issue
Block a user