问题描述:
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
分析:该问题表面上要求交换节点,实际上,只需交换节点对应的数值接口。这样可使用两个指针,然后两个指针交替向下发展。
代码如下:0ms
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* swapPairs(struct ListNode* head) {
if(!head||!head->next)
return head;
struct ListNode *first=head,*second=head->next;
int tmp;
while(second!=NULL){
tmp = first->val;
first->val = second->val;
second->val = tmp;
if(second->next!=NULL){
first = second->next;
second = first->next;
}else
break;
}
return head;
}