描述
给一个链表,两两交换其中的节点,然后返回交换后的链表。
您在真实的面试中是否遇到过这个题? 是
样例
给出 1->2->3->4
, 你应该返回的链表是 2->1->4->3
。
挑战
你的算法只能使用常数的额外空间,并且不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
题目链接
程序
/**
* Definition of singly-linked-list:
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: a ListNode
* @return: a ListNode
*/
ListNode * swapPairs(ListNode * head) {
// write your code here
// 使用常数的额外空间,并且实际的进行节点交换
if(head == NULL || head->next == NULL)
return head;
ListNode *dummpy = new ListNode(0);
dummpy->next = head;
ListNode *pre = dummpy, *cur = head;
while(cur != NULL && cur->next != NULL){
if(cur->next->next != NULL){
ListNode *tmp = cur->next->next;
pre->next = cur->next;
cur->next->next = cur;
cur->next = tmp;
pre = cur;
cur = tmp;
}
else{//到链表尾部
pre->next = cur->next;
cur->next->next = cur;
cur->next = NULL;
}
}
return dummpy->next;
}
};