首页 > 其他 > 详细

206. 反转链表

时间:2020-03-02 12:49:36      阅读:62      评论:0      收藏:0      [点我收藏+]

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;
}

输出结果:

技术分享图片

206. 反转链表

原文:https://www.cnblogs.com/xgp123/p/12394534.html

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