题目链接:
https://leetcode-cn.com/problems/swap-nodes-in-pairs/
代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null) {return head;}
ListNode cur = new ListNode(0);
ListNode ans = new ListNode(0);
cur.next = head;
int count = 0;
while(cur.next != null){
count++;
if(cur.next.next == null) break;
ListNode temp = cur.next;
cur.next = cur.next.next;
temp.next = cur.next.next;
cur.next.next = temp;
if(count == 1) ans = cur.next;
cur = temp;
}
return ans;
}
}
使用的是代码随想录Carl提供的思路,创建一个哑节点接在头部,这样每三个节点进行一次交换节点的操作,while循环内判断一下,如果剩下的节点是单数,就不作操作直接break,如果是双数就进行一次操作,while循坏外将空链表和长度为1的链表都直接返回了。