LeetCode_206. Reverse Linked List

时间:2022-01-28 18:51: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));
}
}