交换链表中的相邻节点
2013-04-24 11:33
344 查看
LeetCode中的题:
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.
分析:先交换链表的前两个节点,接下来每两个相邻节点可以通过重复的操作实现。
代码如下:
//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) {
if(head==NULL)return NULL;
if(head->next==NULL)return head;
ListNode *tmp1=head;
head=head->next;
ListNode *tmp2=head->next;
head->next=tmp1;
tmp1->next=tmp2;
//ListNode *headtmp=head;
while(tmp1->next!=NULL&&tmp1->next->next!=NULL)
{
tmp2=tmp1->next;
tmp1->next=tmp2->next;
ListNode *tmp3=tmp2->next->next;
tmp1->next->next=tmp2;
tmp2->next=tmp3;
tmp1=tmp2;
}
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.
分析:先交换链表的前两个节点,接下来每两个相邻节点可以通过重复的操作实现。
代码如下:
//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) {
if(head==NULL)return NULL;
if(head->next==NULL)return head;
ListNode *tmp1=head;
head=head->next;
ListNode *tmp2=head->next;
head->next=tmp1;
tmp1->next=tmp2;
//ListNode *headtmp=head;
while(tmp1->next!=NULL&&tmp1->next->next!=NULL)
{
tmp2=tmp1->next;
tmp1->next=tmp2->next;
ListNode *tmp3=tmp2->next->next;
tmp1->next->next=tmp2;
tmp2->next=tmp3;
tmp1=tmp2;
}
return head;
}
};
相关文章推荐
- leetcode24,交换链表相邻的节点
- 单链表相邻两个节点之间交换顺序
- Swap Nodes in Pairs 链表交换相邻的节点
- leetcode-24,交换链表相邻节点,递归实现
- 交换单向链表的相邻节点
- Java单链表基本操作(九)--交换相邻节点对的值
- 交换链表中相邻节点的位置
- 交换链表相邻节点
- 给定一个链表,交换每两个相邻节点并返回其头部。
- LintCode 两两交换链表中的节点
- 作业4.451:两两交换链表中的节点
- 两两交换链表中的节点
- 链表节点交换
- 两两交换链表中的节点
- Leetcode:Swap Nodes in Pairs 单链表相邻两节点逆置
- 链表的快速排序(递归,交换节点数据)
- 成对交换链表节点
- 单链表进行排序-通过节点交换,不通过值交换
- 交换链表中两个节点
- 交换单链表中相邻的两个点(人搜)