美文网首页
35. 翻转链表

35. 翻转链表

作者: 6默默Welsh | 来源:发表于2018-02-16 08:32 被阅读41次

    描述

    翻转一个链表

    样例

    给出一个链表1->2->3->null,这个翻转后的链表为3->2->1->null

    挑战

    在原地一次翻转完成

    代码

    /**
     * Definition for ListNode.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int val) {
     *         this.val = val;
     *         this.next = null;
     *     }
     * }
     */
    
    1. 两根指针
    public class Solution {
        /*
         * @param head: n
         * @return: The new head of reversed linked list.
         */
        public ListNode reverse(ListNode head) {
            if (head == null || head.next == null) {
                return head;
            }
            
            ListNode prev = null;
            while (head != null) {
                ListNode temp = head.next;
                head.next = prev;
                // 两行的赋值顺序别写反了
                prev = head;
                head = temp;
            }
            
            return prev;
        }
    }
    
    1. 用递归
    public class Solution {
        /*
         * @param head: n
         * @return: The new head of reversed linked list.
         */
        public ListNode reverse(ListNode head) {
            if (head == null || head.next == null) {
                return head;
            }
            
            // 从 head.next 开始所有链表全部被翻转
            // 但不包括 head.next 的前向指针
            ListNode p = reverse(head.next);
            head.next.next = head;
            head.next = null;
            
            // 返回链表头结点
            return p;
        }
    }
    

    相关文章

      网友评论

          本文标题:35. 翻转链表

          本文链接:https://www.haomeiwen.com/subject/xatptftx.html