Swap Nodes in Pairs
2015-06-10 22:22
543 查看
题目:
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
思路:
两两进行,交换,注意设定好交换节点,防止链表断裂,或是采用递归形式
代码:
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(head==NULL || head->next==NULL) return head;
ListNode *first=head;
ListNode *pre=head;;
ListNode *second;
second=first->next;//单独处理头结点
first->next=second->next;
second->next=first;
head=second;
pre=first;
first=first->next;
while(first!=NULL&&first->next!=NULL)//注意&&的前后顺序
{
second=first->next;
first->next=second->next;
second->next=first;
pre->next=second;
pre=first;
first=first->next;
}
return head;
}
ListNode *swapPairs2(ListNode *head) //递归法,清晰明了
{
if(!head) return NULL;
if(head->next)
{
ListNode *temp = head, *nextHead = head->next->next;
head = head->next;
head->next = temp;
head->next->next = swapPairs(nextHead);
}
return head;
}
};
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 ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(head==NULL || head->next==NULL) return head;
ListNode *first=head;
ListNode *pre=head;;
ListNode *second;
second=first->next;//单独处理头结点
first->next=second->next;
second->next=first;
head=second;
pre=first;
first=first->next;
while(first!=NULL&&first->next!=NULL)//注意&&的前后顺序
{
second=first->next;
first->next=second->next;
second->next=first;
pre->next=second;
pre=first;
first=first->next;
}
return head;
}
ListNode *swapPairs2(ListNode *head) //递归法,清晰明了
{
if(!head) return NULL;
if(head->next)
{
ListNode *temp = head, *nextHead = head->next->next;
head = head->next;
head->next = temp;
head->next->next = swapPairs(nextHead);
}
return head;
}
};
相关文章推荐
- mac平台下面nodejs环境搭配
- Leetcode[19]-Remove Nth Node From End of List
- nodejs全局变量
- nodejs supervisor
- nodejs 运行
- leetcode 25 -- Reverse Nodes in k-Group
- inode、软连接、硬链接
- 让你的 Node.js 应用跑得更快的 10 个技巧(转)
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Count Complete Tree Nodes || LeetCode1
- Count Complete Tree Nodes || LeetCode
- LeetCode_25---Reverse Nodes in k-Group
- Populating Next Right Pointers in Each Node I or II
- Node.js开发框架Express学习笔记(一)搭建开发环境
- Node.js 调试 GC 以及内存暴涨的分析
- 2015年最佳的15个 Node.js 开发工具
- Node.js学习--基础知识(1)--入门
- NodeJs测试
- NodeJS异常处理uncaughtException篇