206. 反转链表

反转一个单链表。  示例:  输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL

 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  //递归方法
10 class Solution {
11     public ListNode reverseList(ListNode head) {
12         if(head==null){
13             return head;
14         }
15         ListNode tmp = reverse(null,head);
16         return tmp;
17     }
18     public ListNode reverse(ListNode pre,ListNode now){
19         ListNode tmp;
20         if(now.next!=null){
21             tmp = reverse(now,now.next);
22         }else{
23             now.next=pre;
24             return now;
25         }
26         now.next=pre;
27         return tmp;
28     }
29 }
 1  //遍历
 2 class Solution {
 3     public ListNode reverseList(ListNode head) {
 4         ListNode pre = null;
 5         ListNode next = null;
 6         ListNode iterator = head;
 7         while(iterator!=null){
 8             next=iterator.next;
 9             iterator.next=pre;
10             pre=iterator;
11             iterator=next;
12         }
13         return pre;
14     }
15 }

 

posted on 2019-11-18 18:55  forever_time  阅读(101)  评论(0编辑  收藏  举报