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