Reverse Linked List

Reverse a singly linked list.

click to show more hints.

Hint:

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

 

Iteratively:

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 public class Solution {
10     public ListNode reverseList(ListNode head) {
11         ListNode first = null;
12         ListNode second = head;
13         while(second != null){
14             ListNode tmp = second.next;
15             second.next = first;
16             first = second;
17             second = tmp;
18         }
19         return first;
20     }
21 }

 

recursively:

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 public class Solution {
10     public ListNode reverseList(ListNode head) {
11         if(head == null || head.next == null) return head;
12         ListNode nextNode = head.next;
13         head.next = null;
14         ListNode newHead = reverseList(nextNode);
15         nextNode.next = head;
16         return newHead;
17     }
18 }

 

posted on 2015-05-07 12:13  Step-BY-Step  阅读(269)  评论(0编辑  收藏  举报

导航