LeetCode206——反转链表

我的LeetCode代码仓:https://github.com/617076674/LeetCode

原题链接:https://leetcode-cn.com/problems/reverse-linked-list/description/

题目描述:

知识点:链表
思路一:递归地反转链表

递归的终止条件:

(1)head为null,直接返回head。

(2)head.next为null,直接返回head。

递归的过程:

我们新的头节点记为newHead,其值应该是翻转以head.next为头节点的链表的结果。同时把head放在head.next的后面,并令head.next为null,这样我们就把head元素放在了新链表的末尾。

由于涉及到递归,而每一次递归的时间复杂度都是O(1)级别的,因此时间复杂度和空间复杂度都是O(n)级别的,其中n为链表中的节点个数。

JAVA代码:

    public class Solution {
        
        public ListNode reverseList(ListNode head) {
            if(head == null || head.next == null) {
                return head;
            }
            ListNode newHead = reverseList(head.next);
            head.next.next = head;
            head.next = null;
            return newHead;
        }
    }

LeetCode解题报告:

思路二:非递归地反转链表

链表相关的题,多设指针,在草稿纸上多演练几次,一定能够轻松解决。

设立虚拟头节点dummyHead和三个指针cur1、cur2、cur3反转链表。

令cur1指向虚拟头节点dummyHead。

如果cur1.next是一个空节点或者说cur1.next.next是一个空节点,即链表中没有节点或链表中只有一个节点,无需翻转,直接返回head即可。

令cur2指向cur1.next,cur3指向cur2.next。在我的定义中,cur2指向的是待处理节点的前一个节点,cur3指向的是待处理节点。只要cur3不为null,就进行以下循环。

(1)令cur2.next指向cur3.next。

(2)设立临时变量temp存储cur1.next结点。令cur1.next节点指向cur3,即将待处理节点放在第一个节点的位置,而令cur3.next为temp。

(3)更新cur3的值为cur2.next。

最后我们返回翻转后的结果dummyHead.next即可。

时间复杂度是O(n)级别的,其中n为链表中的节点数。空间复杂度是O(1)级别的。

JAVA代码:

    public class Solution {
        
        public ListNode reverseList(ListNode head) {
            ListNode dummyHead = new ListNode(-1);
            dummyHead.next = head;
            ListNode cur1 = dummyHead;
            if(cur1.next == null || cur1.next.next == null) {
                return head;
            }
            ListNode cur2 = cur1.next;
            ListNode cur3 = cur2.next;
            while(cur3 != null) {
                cur2.next = cur3.next;
                ListNode temp = cur1.next;
                cur1.next = cur3;
                cur3.next = temp;
                cur3 = cur2.next;
            }
            return dummyHead.next;
        }
    }

LeetCode解题报告:

 
---------------------
作者:清風逐尘乀
来源:CSDN
原文:https://blog.csdn.net/qq_41231926/article/details/82377446
版权声明:本文为博主原创文章,转载请附上博文链接!

posted @ 2019-07-27 20:38  天涯海角路  阅读(112)  评论(0)    收藏  举报