zoukankan      html  css  js  c++  java
  • 206. 反转链表

    206. 反转链表

    1、题目介绍

    反转一个单链表。

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

    2、双指针做法

    2.1、java

        public static ListNode reverseList(ListNode head) {
            if(head == null) return null;
            //构造头指针
            ListNode index = new ListNode(-1);
            index.next = head;
    
            ListNode pCurrent = head;
            while (pCurrent.next != null) {
                //使辅助移动到最后
                pCurrent = pCurrent.next;
            }
    
            while (index.next != pCurrent) {
                ListNode temp = index.next;
                index.next = temp.next;
                temp.next = pCurrent.next;
                pCurrent.next = temp;
            }
    
            return index.next;
        }
    

    输出结果:

    2.2、C

    struct ListNode* reverseList(struct ListNode* head){
            if(head == NULL) return NULL;
            //构造头指针
            struct ListNode* index = (struct ListNode*)malloc(sizeof(struct ListNode));
            index->val = -1;
            index->next = head;
    
            struct ListNode* pCurrent = head;
            while (pCurrent->next != NULL) {
                //使辅助移动到最后
                pCurrent = pCurrent->next;
            }
    
            while (index->next != pCurrent) {
                struct ListNode* temp = index->next;
                index->next = temp->next;
                temp->next = pCurrent->next;
                pCurrent->next = temp;
            }
    
            return index->next;
    }
    

    输出结果:

    3、递归做法

    3.1、java

        public static ListNode reverseList(ListNode head) {
            if(head == null || head.next == null) return head;
    
    //        0、1->2->3->4->5->null
    //        1、2->3->4->5->null
    //        2、3->4->5->null
    //        3、4->5->null
    //        4、5->null
    //        5
            ListNode newNode = reverseList(head.next);
    
    //        System.out.println(head);
    
            head.next.next = head;
            head.next = null;
    
            return newNode;
        }
    

    输出结果:

    3.2、C

    struct ListNode* reverseList(struct ListNode* head){
        if(head == NULL || head->next == NULL) return head;
    
        struct ListNode* newNode = reverseList(head->next);
    
        head->next->next = head;
        head->next = NULL;
    
        return newNode;
    }
    

    输出结果:

  • 相关阅读:
    《构建之法阅读笔记02》
    《人月神话阅读笔记01》
    第四周学习进度条
    子数组2
    敏捷开发方法综述
    子数组1
    第三周学习进度条
    四则运算3
    第二周学习进度条
    四则运算4
  • 原文地址:https://www.cnblogs.com/xgp123/p/12394534.html
Copyright © 2011-2022 走看看