LeetCode OJ--Swap Nodes in Pairs

时间:2024-05-05 11:36:14

https://oj.leetcode.com/problems/swap-nodes-in-pairs/

链表的处理

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *swapPairs(ListNode *head) {
ListNode *dummy = new ListNode(-);
if(head == NULL)
return dummy->next; dummy->next = head; ListNode *tail = dummy; ListNode *current = head;
ListNode *second = head->next;
while(current && second)
{
tail->next = second;
current->next = second->next;
second->next = current; current = current->next;
if(current == NULL)
break;
second = current->next;
tail = tail->next;
tail = tail->next; }
return dummy->next;
}
};