206. Reverse Linked List

Easy

Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

Follow up:

A linked list can be reversed either iteratively or recursively. Could you implement both?

package leetcode.easy;

/**
* Definition for singly-linked list. public class ListNode { int val; ListNode
* next; ListNode(int x) { val = x; } }
*/
public class ReverseLinkedList {
private static void print(ListNode head) {
if (head == null) {
return;
}
while (head != null) {
System.out.print(head.val);
if (head.next != null) {
System.out.print("->");
}
head = head.next;
}
System.out.println("->NULL");
} public ListNode reverseList(ListNode head) {
ListNode nextNode = null;
ListNode curr = head;
while (curr != null) {
ListNode tempNext = curr.next;
curr.next = nextNode;
nextNode = curr;
curr = tempNext;
}
return nextNode;
} @org.junit.Test
public void test() {
ListNode ln1 = new ListNode(1);
ListNode ln2 = new ListNode(2);
ListNode ln3 = new ListNode(3);
ListNode ln4 = new ListNode(4);
ListNode ln5 = new ListNode(5);
ln1.next = ln2;
ln2.next = ln3;
ln3.next = ln4;
ln4.next = ln5;
ln5.next = null;
print(ln1);
print(reverseList(ln1));
}
}

最新文章

  1. SQL Server Reporting Service(SSRS) 第一篇 我的第一个SSRS例子
  2. PHOTOSHOP 半透明方格
  3. o] TortoiseGit错误 - Could not get all refs. libgit2 returned: corrupted loose reference file
  4. HTML总结1
  5. java windows自动化-mail自动发邮件
  6. LOJ #6043. 「雅礼集训 2017 Day7」蛐蛐国的修墙方案
  7. <c:out>标签中的escapeXML属性
  8. 查看oracle 用户执行的sql语句历史记录
  9. MATLAB数值分析实验
  10. 基于RHEL6.3 安装MySQL踩过的坑
  11. video组件的使用
  12. C# AOP框架入门(转)
  13. Java API方式调用Kafka各种协议
  14. Chrome谷歌浏览器已停用不支持的扩展程序解决方法
  15. jpetStore 学习总结(1)
  16. DateFormat多线程使用问题
  17. 洛谷P3690 【模板】Link Cut Tree (LCT)
  18. 输出JS代码中的变量内容
  19. Codeforces - 规律题 [占坑]
  20. Linux 文件上传Linux服务器

热门文章

  1. JS+rem,移动端适配
  2. Go奇技淫巧
  3. 通过map文件找程序崩溃的代码行
  4. Dominating Patterns (AC 自动鸡模版题, 出现次数最多的子串)
  5. Python学习之--用户输入以及运算
  6. Firefox修復QQ快速登錄
  7. 最长升序列 DP
  8. 2019暑期金华集训 Day7 分治
  9. Pytest权威教程10-捕获警告信息
  10. [WEB安全]SSRF中URL的伪协议