首页 > 其他 > 详细

剑指Offer:反转列表(24)

时间:2020-08-21 11:22:36      阅读:64      评论:0      收藏:0      [点我收藏+]

题目描述:

输入一个链表,反转链表后,输出新链表的表头。

解题思路:

比较简单,直接上代码

递归:

1 public ListNode ReverseList(ListNode head) {
2     if (head == null || head.next == null)
3         return head;
4     ListNode next = head.next;
5     head.next = null;
6     ListNode newHead = ReverseList(next);
7     next.next = head;
8     return newHead;
9 }

迭代:

 1 class Solution {
 2     public ListNode reverseList(ListNode head) {
 3         //申请节点,pre和 cur,pre指向null
 4         ListNode pre = null;
 5         ListNode cur = head;
 6         ListNode tmp = null;
 7         while(cur!=null) {
 8             //记录当前节点的下一个节点
 9             tmp = cur.next;
10             //然后将当前节点指向pre
11             cur.next = pre;
12             //pre和cur节点都前进一位
13             pre = cur;
14             cur = tmp;
15         }
16         return pre;
17     }
18 }

 

剑指Offer:反转列表(24)

原文:https://www.cnblogs.com/lkylin/p/13539385.html

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