反转链表

反转链表

描述

定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

头插法

链表要注意很多细节,比如上面例子最后1的next要指向NULL,不然会无线循环,超时,还有很多细节需要注意。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(head==NULL || head->next==NULL)
            return head;
        ListNode *p = new ListNode(-1);
        p->next = head;
        ListNode* cur = head->next;
        ListNode* next;
        head->next = NULL;
        while(cur != NULL)
        {
            next = cur->next;
            cur->next = p->next;
            p->next = cur;
            cur = next;
        }
        return p->next;
    }
};
迭代反转

一个cur,一个pre指向下一个结点

  • ListNode* t = pre->next;
  • pre->next = cur;
  • cur = pre;
  • pre = t;
    可用例子具体分析一下会理解更透彻
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(head==NULL || head->next==NULL)
            return head;
        ListNode* cur = head;
        ListNode* pre = NULL;
        while(cur!=NULL)
        {
            ListNode* temp = cur->next;
            cur->next = pre;
            pre = cur;
            cur = temp;
        }
        return pre;
    }
};

反转链表2

描述

反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。

说明:
1 ≤ m ≤ n ≤ 链表长度。

示例:

输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL

思路和代码

和上一题不同的是设置了一个反转的区间

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseBetween(ListNode* head, int m, int n) {
        ListNode* dummy = new ListNode(-1);
        ListNode* pre = dummy;
        dummy->next = head;
        for(int i=0; i<m-1; i++)
            pre = pre->next;
        ListNode* head2 = pre;
        pre = pre->next;
        ListNode* cur = pre->next;
        for(int i=m; i<n; i++)
        {
            pre->next = cur->next;
            cur->next = head2->next;
            head2->next = cur;
            cur = pre->next;
        }
        return dummy->next;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值