Swap Nodes in Pairs
2016-05-30 11:05
441 查看
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *swapPairs(ListNode *head) {
ListNode** curNext = &head;
while(NULL != *curNext && NULL != (*curNext)->next)
{
ListNode* temp = (*curNext)->next;
(*curNext)->next = (*curNext)->next->next;
temp->next = *curNext;
*curNext = temp;
curNext = &(*curNext)->next->next;
}
return head;
}
};
在网上搜到了这份代码,用二级指针的方法解决pre节点的指向问题。其中二级指针curNext起了两个作用,一个是持有节点的地址,供其他节点指过来,一个是持有指针的地址,用解运算修饰符*修改指针的指向。
当然,直接用一级指针容易理解一些,不过需要在循环中做一次指针是否为空的判断:
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *swapPairs(ListNode *head) {
ListNode** curNext = &head;
while(NULL != *curNext && NULL != (*curNext)->next)
{
ListNode* temp = (*curNext)->next;
(*curNext)->next = (*curNext)->next->next;
temp->next = *curNext;
*curNext = temp;
curNext = &(*curNext)->next->next;
}
return head;
}
};
在网上搜到了这份代码,用二级指针的方法解决pre节点的指向问题。其中二级指针curNext起了两个作用,一个是持有节点的地址,供其他节点指过来,一个是持有指针的地址,用解运算修饰符*修改指针的指向。
当然,直接用一级指针容易理解一些,不过需要在循环中做一次指针是否为空的判断:
ListNode *swapPairs(ListNode *head) { ListNode *first, *second, *temp; if (!head || !head->next) { return head; } else { first = head; second = first->next; head = second; temp = first; while (first && second) { temp->next = second; first->next = second->next; second->next = first; temp = first; first = first->next; if (first != NULL) { second = first->next; } } return head; } }
相关文章推荐
- Nodejs动态加载路由,Nodejs遍历目录,Nodejs路由工具
- node 基础process
- C# TreeView nodeMouseClick 的使用
- [leetcode] 237. Delete Node in a Linked List
- Hdfs(NameNode&DataNode)和Hive迁移总结
- Nodejs动态加载路由,Nodejs遍历目录,Nodejs路由工具
- node.js之express-安装和helloword实例
- [nodejs]mongoose学习1
- nodeName - nodeValue
- node中的path模块
- <LeetCode OJ> 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs [easy] (Python)
- RabbitMQ 基础教程(1) - Hello World
- nodejs抓取网页的源码,并保存到本地文件
- 《Nodejs开发加密货币》之十六:利益,魔鬼与天使的共同目标
- Hello Hexo
- 安装Node和NPM
- nodejs安装
- leetcode 24 Swap Nodes in Pairs C++
- mybatis---源码分析----xml解析----XNode