1.问题描述 https://leetcode-cn.com/problems/swap-nodes-in-pairs/comments/
2.解题代码
/*
* @lc app=leetcode.cn id=24 lang=csharp
*
* [24] 两两交换链表中的节点
*/
// @lc code=start
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }
*/
public class Solution {
public ListNode SwapPairs(ListNode head) {
if (head == null)
{
return head;
}
ListNode node_1 = head;
ListNode node_2 = head.next;
ListNode nodeReturn = node_2 == null ? node_1 : node_2;
ListNode nodeSecond = null;
while (node_1 != null && node_2 != null)
{
ListNode listNextNode = node_2.next;
node_1.next = node_2.next;
node_2.next = node_1;
if (nodeSecond != null)
{
nodeSecond.next = node_2;
}
if (listNextNode == null || listNextNode.next == null)
{
break;
}
nodeSecond = node_1;
node_1 = listNextNode;
node_2 = listNextNode.next;
}
return nodeReturn;
}
}
// @lc code=end
|