[LeedCode OJ]#24 Swap Nodes in Pairs
2015-09-06 21:04
591 查看
【 声明:版权所有,转载请标明出处,请勿用于商业用途。 联系信箱:libin493073668@sina.com】
题目链接:https://leetcode.com/problems/swap-nodes-in-pairs/
题意:
给你一个链表,要你对每两个相邻的节点进行交换
思路:
链表的结点不用想都知道通过next的指向来找,交换也是如此,通过改变指向就行了,但是注意要将尾结点的next指向空,否则要超时
题目链接:https://leetcode.com/problems/swap-nodes-in-pairs/
题意:
给你一个链表,要你对每两个相邻的节点进行交换
思路:
链表的结点不用想都知道通过next的指向来找,交换也是如此,通过改变指向就行了,但是注意要将尾结点的next指向空,否则要超时
/** * 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==nullptr || head->next==nullptr) return head; ListNode *newlist = new ListNode(0); ListNode *ptr = newlist; ListNode *cur = head; while(cur && cur->next) { ListNode *pnext = cur->next->next; ptr->next = cur->next; ptr = ptr->next; ptr->next = cur; ptr = ptr->next; ptr->next = nullptr; cur = pnext; } if(cur) ptr->next = cur; return newlist->next; } };
相关文章推荐
- nodejs安装不了和npm安装不了的解决方法
- LeetCode题解:Swap Nodes in Pairs
- node.js的"Cannot enqueue Handshake after invoking quit"错误
- hadoop2.x 如何解决NameNode单节点故障问题?
- Node.js 初窥
- Understanding nodejs
- nodeJS删除文件
- 用nodejs解析json数据
- Swap Nodes in Pairs
- LeetCode -- Delete Node in a Linked List
- org.w3c.dom.Node 转换成xml string
- [leetcode]51 Delete Node in a Linked List
- Node.js开发入门—使用对话框ngDialog
- [LeetCode#24]Swap Nodes in Pairs
- 学习nodejs之hello world
- 学习nodejs之restful
- NodeJS入门(五)—— process对象
- leetcode: (41) Populating Next Right Pointers in Each Node
- 基于nodejs实现js后端化处理
- Nodejs-模块-connect源码浅析