LeetCode-024:Swap Nodes in Pairs
程序员文章站
2024-03-21 13:10:34
...
题目:
Given a linked list, swap every two adjacent nodes and return its head.
Example:
Given1->2->3->4
, you should return the list as2->1->4->3
.
Note:
- Your algorithm should use only constant extra space.
- You may not modify the values in the list's nodes, only nodes itself may be changed.
题意:
交换单链表中每对节点的空间!!!
思路:
水题~
Code:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode *nhead=new ListNode(0);
nhead->next=head;
ListNode *pre=nhead,*cur=head;
while(cur&&cur->next){
pre->next=cur->next;
cur->next=pre->next->next;
pre->next->next=cur;
pre=cur;
cur=cur->next;
}
return nhead->next;
}
};
推荐阅读
-
LeetCode-024:Swap Nodes in Pairs
-
Leetcode 1530. Number of Good Leaf Nodes Pairs (python)
-
Leetcode——24. Swap Nodes in Pairs
-
24. Swap Nodes in Pairs
-
LeetCode 24. Swap Nodes in Pairs
-
LeetCode 24. Swap Nodes in Pairs
-
24. Swap Nodes in Pairs
-
24. Swap Nodes in Pairs。
-
leetcode 24. Swap Nodes in Pairs 每两个结点反转一次
-
Swap Nodes in Pairs