2 Star 10 Fork 2

CG国斌 / myleetcode

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
_206.java 1.05 KB
一键复制 编辑 原始数据 按行查看 历史
Charies Gavin 提交于 2020-02-06 12:44 . 初始化 myleetcode 项目
package com.hit.basmath.learn.linked_list;
import com.hit.common.ListNode;
/**
* 206. Reverse Linked List
* <p>
* Reverse a singly linked list.
* <p>
* Example:
* <p>
* Input: 1->2->3->4->5->NULL
* <p>
* Output: 5->4->3->2->1->NULL
* <p>
* Follow up:
* <p>
* A linked list can be reversed either iteratively or recursively. Could you implement both?
*/
public class _206 {
/**
* iterative solution
*/
public ListNode reverseList(ListNode head) {
ListNode newHead = null;
while (head != null) {
ListNode nextNode = head.next;
head.next = newHead;
newHead = head;
head = nextNode;
}
return newHead;
}
/**
* recursive solution
*/
public ListNode reverseList2(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode nextNode = head.next;
ListNode newHead = reverseList2(nextNode);
nextNode.next = head;
head.next = null;
return newHead;
}
}
Java
1
https://gitee.com/guobinhit/myleetcode.git
git@gitee.com:guobinhit/myleetcode.git
guobinhit
myleetcode
myleetcode
master

搜索帮助