Total Accepted: 84289
Total Submissions: 243534
Difficulty: Medium
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.
AC(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* dummy, *prev, *nextNode;
dummy = head;
prev = nextNode = NULL;
while(dummy != NULL && dummy->next != NULL){
nextNode = dummy->next;
dummy->next = nextNode->next;
nextNode->next = dummy;
if(prev)
prev->next = nextNode;
else
head = nextNode;
prev = dummy;
dummy = dummy->next;
}
return head;
}
分析:
跟反转的某一种方法有点像。
此题要注意的是 第一个pair 跟之后的pair 处理不一样:之后的pair还需要跟前面已经处理好的黏起来,而第一个pair前面是没东西可粘的!所以加一个if判断是不是第一个pair
本文介绍了一种链表操作算法——成对交换相邻节点的方法,并提供了0ms的最快实现方案。该算法仅使用常数空间,不改变列表值,只变更节点连接。
363

被折叠的 条评论
为什么被折叠?



