leetcode之24. Swap Nodes in Pairs(C++实现&链表实现和整体测试)
来源:互联网 发布:python 清空文件夹 编辑:程序博客网 时间:2024/06/16 23:03
题目:
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 linkedlist{public: linkedlist(): head(nullptr) {}; ~linkedlist(); void inserts(int val); ListNode* swapPairs(ListNode* head); void prints();//private: ListNode *head;};void linkedlist::prints(){ if(head==nullptr) { cout<<"The Linkedlist is empty"<<endl; return ; } cout<<head->val; ListNode * heads=head->next; while(heads) { cout<<" -> "<<heads->val; heads=heads->next; } cout<<endl;}ListNode* linkedlist::swapPairs(ListNode* head){ if(!head || !head->next) return head; ListNode* temp; ListNode* new_head; //change num1 & num2 ListNode* p1=head; ListNode* p2=head->next; p1->next=p2->next; p2->next=p1; head=p2; ListNode* p=head->next; while(p->next && p->next->next) { //init temp=p->next; new_head=temp->next; p->next=new_head; temp->next=new_head->next; new_head->next=temp; //update p p=temp; } return head;}void linkedlist::inserts(int val){ if(nullptr==head) { head=new ListNode(val); } else { ListNode *heads = head; while(heads->next) { heads=heads->next; } heads->next=new ListNode(val); } cout<<"insert success!"<<endl; return ;}int main(){ linkedlist* s = new linkedlist(); s->prints(); s->inserts(1); s->inserts(2); s->inserts(3); s->inserts(4); s->inserts(5); s->prints(); s->head=s->swapPairs(s->head); s->prints(); return 0;}
0 0
- leetcode之24. Swap Nodes in Pairs(C++实现&链表实现和整体测试)
- LeetCode 之 Swap Nodes in Pairs — C 实现
- leetcode Swap Nodes in Pairs java实现
- 【C++】【LeetCode】24. Swap Nodes in Pairs
- leetcode解题之24. Swap Nodes in Pairs java 版(成对翻转链表)
- 24. Swap Nodes in Pairs (java实现)
- leetcode 24. Swap Nodes in Pairs 单向链表操作
- leetcode: Swap Nodes in Pairs (C++)
- 【LeetCode-24】Swap Nodes in Pairs(C++)
- Leetcode c语言-Swap Nodes in Pairs
- leetcode之Swap Nodes in Pairs
- LeetCode 之 Swap Nodes in Pairs
- LeetCode之Swap Nodes in Pairs
- LeetCode之Swap Nodes in Pairs
- LeetCode之Swap Nodes in Pairs
- 【LeetCode】之Swap Nodes in Pairs
- 【Leetcode】之Swap Nodes in Pairs
- leetcode之Swap Nodes in Pairs
- mysql 1045 登录失败
- /etc/sysctl.conf 参数说明
- 最简单的文件加解密算法
- [解决]java.io.IOException: Cannot obtain block length for LocatedBlock
- oracle client
- leetcode之24. Swap Nodes in Pairs(C++实现&链表实现和整体测试)
- 创建含数字字母的随机字符串方法
- 【38.96%】【hdu 1540】Tunnel Warfare
- code snippets
- Bzoj2595: [Wc2008]游览计划
- class-dump -H test.decrypted -o test不能导出头文件的解决方法
- bootstrap导航插件wizard--源码demo
- C++11 并发指南三(std::mutex 详解)
- BFC原理