Swap Nodes in Pairs
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.
struct Node
{
int val;
Node *next;
Node(int x) : val(x), next(NULL){}
};
Node* fun(Node *head)
{
if (head == NULL)
{
return NULL;
}
Node *result = head;
Node *p = head;
Node *q = p->next;
Node *prev = NULL;
while (p != NULL && q != NULL)
{
Node *temp = q->next;
if (result == head)
{
result = q;
}
else
{
prev->next = q;
}
q->next = p;
p->next = temp;
prev = p;
p = temp;
if (p != NULL)
{
q = p->next;
}
}
return result;
}
相關文章
- 024,Swap Nodes in PairsAI
- 24. Swap Nodes in PairsAI
- Leetcode Swap Nodes in PairsLeetCodeAI
- Leetcode 24 Swap Nodes in PairsLeetCodeAI
- LeetCode 24 Swap Nodes in PairsLeetCodeAI
- Leetcode-Swap Nodes in PairsLeetCodeAI
- Swap Nodes in Pairs leetcode javaAILeetCodeJava
- Leetcode 線性表 Swap Nodes in PairsLeetCodeAI
- [LeetCode] Swap Nodes in Pairs 成對交換節點LeetCodeAI
- 兩種解法搞定Swap Nodes in Pairs演算法題AI演算法
- 【LeetCode】Swap Nodes in Pairs 連結串列指標的應用LeetCodeAI指標
- 【leetcode】24. Swap Nodes in Pairs 連結串列奇偶節點交換LeetCodeAI
- Palindrome PairsAI
- 11.2.0.1 rac 2nodes asm aix6.1 orarootagent.bin swap memory記憶體洩漏ASMAI記憶體
- 11.2.0.1 rac 2nodes asm aix6.1 orarootagent.bin swap memory記憶體洩漏ASMAI記憶體
- 13-Architecture-nodes
- 【Lintcode】572. Music PairsAI
- 1512. Number of Good PairsGoAI
- LeetCode-Palindrome PairsLeetCodeAI
- 532. K-diff Pairs in an ArrayAI
- HINT no_swap_join_inputs/swap_join_inputs
- Vim auto-pairs設定選項AI
- 【LeetCode】Palindrome Pairs(336)LeetCodeAI
- [LeetCode] 336. Palindrome PairsLeetCodeAI
- Diff-prime Pairs(思維+素數篩)AI
- LeetCode677. Map Sum PairsLeetCodeAI
- LeetCode-Find K Pairs with Smallest SumsLeetCodeAI
- IPP SWAP孵化器|IPP SWAP系統開發分析
- Leetcode Reverse Nodes in k-GroupLeetCode
- One cause leads to the error(The specified nodes are not clusterable)Error
- OCR integrity results are inconsistent amongst the nodes.
- get_swap.sh
- MySQL之swap配置MySql
- Linux新增SWAPLinux
- linux swap(交換)Linux
- Lua中ipairs()和pairs()的區別與使用AI
- Leetcode 25 Reverse Nodes in k-GroupLeetCode
- LeetCode-Count Complete Tree NodesLeetCode