/**
* 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 null;
int x = 1;//用来判断head是奇数还是偶数
int temp = 0;
//在遍历head的同时给temp_2赋值,最后返回的结果是result
ListNode temp_2 = new ListNode();
ListNode result = temp_2;
while (null != head)
{
if (x % 2 != 0)
{
temp = head.val;
head = head.next;
if(head != null)
{
temp_2.val = head.val;
temp_2.next = new ListNode();
temp_2 = temp_2.next;
temp_2.val = temp;
}
else
{
temp_2.val = temp;
}
}
else
{
head = head.next;
if(null != head)
{
temp_2.next = new ListNode();
temp_2 = temp_2.next;
}
}
x++;
}
return result;
}
}
LeetCode_两两交换链表中的节点_C#_迭代
最新推荐文章于 2024-07-25 19:34:38 发布