码迷,mamicode.com
首页 > 其他好文 > 详细

Reverse Linked List

时间:2015-05-07 14:20:03      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:

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 }

 

Reverse Linked List

标签:

原文地址:http://www.cnblogs.com/reynold-lei/p/4484464.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!