Reverse a LinkedList 链表倒置
2015-06-16 17:05
302 查看
两种方法倒置一个链表
1. 递归
亮点在于构建一个假的head:newHead,代码如下:class RecursivelyReverseLinkedList{ ListNode newHead = new ListNode(0); public ListNode reverseList(ListNode head) { if(head == null) { return null; } // empty list reverseList(newHead, head); // recursion return newHead.next; } public ListNode reverseList(ListNode head, ListNode p) { head.next = p; // connect the head and the list if(p.next != null) { ListNode p1 = new ListNode(0); // new head ListNode q = reverseList(p1, p.next); // get the last non empty node p.next = null; // to put the p in new list q.next = p; // connect head.next = p1.next; // connect } return p; // return the last non empty node } }
2. 迭代
public ListNode reverseList(ListNode head) { if(head == null) { return null; } // return empty list ListNode newHead = new ListNode(0); // new head ListNode p = head; // temp index while(p != null) { ListNode temp = p; // get off the first node p = p.next; // move to next node temp.next = newHead.next; // connect newHead.next = temp; } return newHead.next; // return the right head }
相关文章推荐
- 手把手教你写专利申请书/如何申请专利
- 离散余弦正逆变换程序
- 【SHARE】WEB前端学习资料
- 伪元素改变date类型input框的默认样式实例页面
- iOS开发经验技巧之IOS界面开发使用viewWithTag:(int)findTag方法获取界面元素
- Win10系统怎么重新开启通知中心突然发现没有了
- yum 命令的使用,及yum仓库的创建
- “WebForms UnobtrusiveValidationMode 需要“jquery”ScriptResourceMapping
- 常用js函数--个人项目总结
- wicket之实现IDataProvider接口,只查询当前页数据
- Java中JTextArea如何添加滚动条
- FireDAC 下的 Sqlite [3] - 获取数据库的基本信息
- NSProcessInfo类方法介绍
- Java初级笔记_面向对象3
- 浅析CentOS和RedHat Linux的区别
- chrome提示"安装unity web player"
- Linux makefile 课程 非常具体的,和理解
- Count Complete Tree Nodes
- 最新Cocos2d-x3.2开发环境搭建(windows环境下)
- [笔记]Emacs笔记:一,Windows下配置Emacs来开发Python