首页 > 其他 > 详细

206. 反转链表

时间:2019-11-18 19:32:26      阅读:75      评论:0      收藏:0      [点我收藏+]

反转一个单链表。  示例:  输入: 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 }

 

206. 反转链表

原文:https://www.cnblogs.com/gongzixiaobaibcy/p/11884299.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!