Leetcode 24. 两两交换链表中的节点
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* swapPairs(struct ListNode* head){
if(head == NULL)
{
return NULL;
}
struct ListNode* cur = head;
struct ListNode* newHead = NULL;
struct ListNode* tail = NULL;
while(cur != NULL)
{
struct ListNode* curNext = cur->next;
if(curNext == NULL)
{
if(newHead != NULL) {
tail ->next = cur;
tail = tail ->next;
}
else
{
newHead = cur;
tail = newHead;
}
break;
}
if(tail == NULL) {
newHead = curNext;
tail = newHead;
curNext = curNext->next;
tail->next = cur;
tail = tail->next;
}
else
{
tail->next = curNext;
tail =tail->next;
curNext = curNext->next;
tail->next = cur;
tail =tail->next;
}
cur = curNext;
}
tail->next = NULL;
return newHead;
}