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.
Subscribe to see which companies asked this question
这个也就是改天两个相邻的节点的值
这段代码使用的试类似交换两个数的值,然后使用了递归,
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* swapPairs(struct ListNode* head) {
if(head==NULL||head->next==NULL) return head;
struct ListNode *tmp=head->next;
head->next=swapPairs(tmp->next);
tmp->next=head;
return tmp;
}
本文介绍了一种链表中相邻节点值的交换算法,并通过递归实现。该算法仅使用常数空间,不修改列表值,仅改变节点连接。适用于需要高效空间利用的场景。
584

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



