题目:
给一个链表,两两交换其中的节点,然后返回交换后的链表。
给出 1->2->3->4
, 你应该返回的链表是 2->1->4->3
。
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/**
* @param head a ListNode
* @return a ListNode
*/
ListNode* swapPairs(ListNode* head) {
// Write your code here
if(head==NULL)
return NULL;
if(head->next==NULL)
return head;
ListNode *temp=head->next;
head->next=temp->next;
temp->next=head;
ListNode *dummy=temp;
ListNode *T=head->next;
while(T!=NULL&&T->next!=NULL)
{ temp=T->next;
head->next=temp;
T->next=temp->next;
temp->next=T;
head=T;
T=T->next;
}
return dummy;
}
/*ListNode *l1=head;
ListNode *l2=head->next;
ListNode *dummy=l2;
head=head->next->next;
while(head!=NULL)
{ l1->next=head;
l2->next=head->next;
head=head->next->next;
}
while(l1!=NULL)
{ ListNode *p1=l1->next;
ListNode *p2=l2->next;
l2->next=l1;
l1->next=p2;
l2=p2;
l1=p1;
}
return dummy;
}
*/
};
//注释掉的就是我一开始做的不对的。
感想:有些题目虽然有非常简便算法,但是时间复杂度或空间复杂度往往随之长高,一开始就把头结点给dummy,然后后续操作都不会改变dummy,感觉这就是链表的重点。