284
技術社區[雲棲]
[LeetCode]24.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.
【題意】
給定一個鏈表,交換每兩個相鄰的節點,並返回它的頭。
你的算法應該使用常數空間。您不得修改在列表中的值,隻有節點本身是可以改變的。
【分析】
無
【代碼】
/*********************************
* 日期:2014-01-29
* 作者:SJF0115
* 題號: 24.Swap Nodes in Pairs
* 來源:https://oj.leetcode.com/problems/swap-nodes-in-pairs/
* 結果:AC
* 來源:LeetCode
* 總結:
**********************************/
#include <iostream>
#include <stdio.h>
#include <algorithm>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *swapPairs(ListNode *head) {
if (head == NULL){
return head;
}
ListNode *dummy = (ListNode*)malloc(sizeof(ListNode));
dummy->next = head;
ListNode *nodeA,*nodeB = NULL;
ListNode *pre = dummy,*cur = head;
//至少2個節點采用交換
while(cur != NULL && cur->next != NULL){
nodeA = cur;
nodeB = cur->next;
//交換
nodeA->next = nodeB->next;
nodeB->next = nodeA;
pre->next = nodeB;
//更新pre,cur
pre = nodeA;
cur = nodeA->next;
}
return dummy->next;
}
};
int main() {
Solution solution;
int A[] = {1,2,3,4,5};
ListNode *head = (ListNode*)malloc(sizeof(ListNode));
head->next = NULL;
ListNode *node;
ListNode *pre = head;
for(int i = 0;i < 4;i++){
node = (ListNode*)malloc(sizeof(ListNode));
node->val = A[i];
node->next = NULL;
pre->next = node;
pre = node;
}
head = solution.swapPairs(head->next);
while(head != NULL){
printf("%d ",head->val);
head = head->next;
}
return 0;
}
【代碼2】
class Solution {
public:
ListNode *swapPairs(ListNode *head) {
return reverseKGroup(head,2);
}
private:
ListNode *reverseKGroup(ListNode *head, int k) {
if (head == NULL || k < 2){
return head;
}
ListNode *dummy = (ListNode*)malloc(sizeof(ListNode));
dummy->next = head;
ListNode *pre = dummy,*cur = NULL,*tail = NULL;
//統計節點個數
int count = 0;
while(pre->next != NULL){
pre = pre->next;
count++;
}
//反轉次數
int rCount = count / k;
int index = 0;
//反轉元素的前一個
pre = dummy;
//反轉元素第一個即翻轉後的尾元素
tail = dummy->next;
//共進行rCount次反轉
while(index < rCount){
int i = k - 1;
//反轉
while(i > 0){
//刪除cur元素
cur = tail->next;
tail->next = cur->next;
//插入cur元素
cur->next = pre->next;
pre->next = cur;
i--;
}
pre = tail;
tail = pre->next;
index++;
}
return dummy->next;
}
};
利用:LeetCode之Reverse Nodes in k-Group
最後更新:2017-04-03 12:54:51
上一篇:
HDU1172 猜數字
下一篇:
HTTP請求和響應格式
selenium簡介-----如何理解selenium-WebDriver
九度題目1339:ACM
阿裏雲雙11活動擼福利攻略雲服務器篇 必買爆款,包年ECS低至240元
如何通過VPC在本機搭建局域網
經典白話算法之歸並排序
Android狀態機(藍牙)
android 加載圖片輕鬆避免OOM(out of memory) 支持設置緩存大小,不再強製catch OOM
實用bash命令記錄
Android開發問題 - Some projects cannot be imported because they already exist in the workspace
html文件中引入js代碼