Leetcode c语言-Swap Nodes in Pairs
来源:互联网 发布:免费瓷砖设计软件 编辑:程序博客网 时间:2024/06/09 14:25
Title:
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.
这道题非常简单,但对于不熟悉链表操作的同学而言,这道题可以让你了解如何交换单链表的节点。细细分析还是能够有所收获的。
下面结合代码分析这道题:
Solution:
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */struct ListNode* swapPairs(struct ListNode* head) { struct ListNode* p=head; struct ListNode* q; if (head==NULL || head->next==NULL) return head; q=p->next; p->next=q->next; q->next=p; head=q; while (p->next!=NULL && p->next->next!=NULL) { q=p->next->next; p->next->next=q->next; q->next=p->next; p->next=q; p=q->next; } return q;}
第一个判断链表是否为0,或者链表是否只有一个节点,是的话不做处理返回head。
接着,新建一个节点q让其等于p->next,也就是第二个节点2。
然后就是将1和2进行对换
p->next=q->next;上面一步是,将q->next,也就是节点3的地址赋给p->next,也就是将节点1的next重新选择为3,而不是2。
q->next=p;
这一步是第一个节点p赋给q->next,也就是交换第一个位置了,q变成第一个了,p变成第二个。
head=q;重新将head指向q,现在q就是首节点。head就是头部。最后返回就返回head。
while (p->next!=NULL && p->next->next!=NULL) { q=p->next->next; p->next->next=q->next; q->next=p->next; p->next=q; p=q->next; }
q=p->next->next;
q等于第四个节点。
p->next->next=q->next;
将q->next也就是第五个节点的地址,赋给p->next,也就是第三节点的next指向第五节点,而不是第四节点。
q->next=p->next;然后p->next也就是第三节点,的地址赋给q->next,也就是三四位置进行交换。
p->next=q;不要忘了将第二节点的next改成第四节点。这点容易被遗忘。
p=q->next;最后,将q->next也就是第四个节点,赋给p,也就是开始进行while循环,类似于p+2,前进2个节点。
阅读全文
0 0
- Leetcode c语言-Swap Nodes in Pairs
- [C语言][LeetCode][24]Swap Nodes in Pairs
- 【LeetCode】24. Swap Nodes in Pairs C语言
- leetcode: Swap Nodes in Pairs (C++)
- 【LeetCode-24】Swap Nodes in Pairs(C++)
- 【C++】【LeetCode】24. Swap Nodes in Pairs
- Swap Nodes in Pairs(C语言)
- LeetCode:Swap Nodes in Pairs
- LeetCode: Swap Nodes in Pairs
- [Leetcode] Swap Nodes in Pairs
- LeetCode : Swap Nodes in Pairs
- [LeetCode] Swap Nodes in Pairs
- Leetcode: Swap nodes in pairs
- [LeetCode]Swap Nodes in Pairs
- [LeetCode]Swap Nodes in Pairs
- LeetCode-Swap Nodes in Pairs
- LeetCode - Swap Nodes in Pairs
- LeetCode | Swap Nodes in Pairs
- 任务列表(360公司2017春招真题)
- What does [B >: A] do in Scala?
- One or more constraints have not been satisfied.
- 5.Schema与数据类型优化
- 设计资源管理类时应注意的细节
- Leetcode c语言-Swap Nodes in Pairs
- 计算机体系结构(一)
- 文章标题
- HashMap
- 二进制补码
- 私人数据
- LeetCode39
- 关于增删改查方法中 public后的 返回值类型
- Android解析JSON,你真的需要三方库?