24.Swap Nodes in Pairs
来源:互联网 发布:冒险岛2黑胖数据 编辑:程序博客网 时间:2024/04/29 04:11
问题:给一个链表,每2个节点交换一次,比如,Given 1->2->3->4
, you should return the list as2->1->4->3
.
思路:只考察链表操作,太简单。
/**
* 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 || head->next==NULL) return head;
//head node
ListNode* new_head=head->next;
head->next=head->next->next;
new_head->next=head;
//process
ListNode* pre_node=head;
while(pre_node->next!=NULL && pre_node->next->next!=NULL){
ListNode* tem_node=pre_node->next->next;
pre_node->next->next=pre_node->next->next->next;
tem_node->next=pre_node->next;
pre_node->next=tem_node;
pre_node=pre_node->next->next;
}
//result
return new_head;
}
};
0 0
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24.Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- WebDriver中断言的使用(一)
- ubuntu 重启网络设置
- Java基础——03—初次认识HelloWorld
- 第四周1003题解
- shell常用特殊变量
- 24.Swap Nodes in Pairs
- WPF中log4net的用法
- [LeetCode] Combinations
- 这个姑娘成了全球最有影响力的人之一(特别会做家务!)
- python中threading的高级函数应用解析 Lock Rlock Condition Semaphore Timer Event Semaphore对象
- 两个栈实现队列
- Android Studio上使用github
- DB2 执行Sql 语句中时的with ur
- Java单例模式——互斥锁-单例之懒汉式的线程安全