Swap Nodes in Pairs
来源:互联网 发布:关于大数据的论文 编辑:程序博客网 时间:2024/05/19 03:17
leetcode上的题目是:
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.
网上很多解法是通过交换链表指针的方式实现,很少有通过交换值来实现的,下面的代码就是通过第二种方式实现:#include"iostream"
using namespace std;
//* Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
};
ListNode *addNewNode(ListNode *head,int b) //function that add a number for a specific list ;
{
ListNode *ptr=head;
if(head==nullptr)
head = new ListNode(b);
else
{
for(; ptr->next!=nullptr; ptr=ptr->next)
;
ptr->next = new ListNode(b);
}
return head;
}
void print_list(ListNode *head) //print node value for a specific list;
{
ListNode *ptr=head;
if(ptr!=nullptr)
{
for(; ptr->next!=nullptr; ptr=ptr->next)
cout<<ptr->val<<"->";
cout<<ptr->val<<endl;
}
}
class Solution {
public:
ListNode *swapPairs(ListNode *head) {
if(head==nullptr||head->next==nullptr)
return head;
int temp;
ListNode *ptr=head;
while(head!=nullptr && head->next!=nullptr)
{
temp=head->val;
head->val=head->next->val;
head->next->val=temp;
head=head->next->next;
}
return ptr;
}
};
int main()
{
ListNode *p1=nullptr,*p2=nullptr;
p1=addNewNode(p1,2);
p1=addNewNode(p1,4);
p1=addNewNode(p1,5);
p1=addNewNode(p1,0);
p1=addNewNode(p1,1);
print_list(p1);
Solution shunf;
ListNode *p3 = shunf.swapPairs(p1);
print_list(p3);
system("pause");
return 0;
}
在vs2012平台下运行如图:
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes In Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- IK Analyzer demo
- C++关键字的详解 ---- mutable关键字
- eclipse相关问题一:无法import项目,显示 select at list one project
- c++在vs2010中操作Mysql的讲解
- 环信sdk的module,titanium也可以做IM即时聊天了
- Swap Nodes in Pairs
- 计算机的性能评价一
- 1011. A+B和C (15)
- 深入浅出Android App耗电量统计
- IOS contentMode属性
- iframe父级与iframe子级间访问
- TCP的拥塞控制
- 神经网络&深度学习
- tyvj1055 沙子合并 (区间dp)