LeetCode_206. Reverse Linked List

 

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;

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));
	}
}

 

Guess you like

Origin www.cnblogs.com/denggelin/p/11731025.html