链表翻转问题
本文最后更新于 26 天前。

1.力扣206翻转链表1

代码思路:首先pre等于空指针,curr是头节点。while循环中1.每次先记录curr之后的节点。2.curr的next指向pre。3.pre和curr向后移。

注意:因为pre初始为空,所以翻转后原来的头节点的next指针也正好指向空

struct ListNode* reverseList(struct ListNode* head) {
    struct ListNode *pre = NULL, *curr = head;
    while(curr != NULL){
        struct ListNode* next = curr->next;
        curr->next = pre;
        pre = curr, curr = next;
    }
    return pre;
}

2.力扣92翻转链表2

注意:使用hair指针指向head头节点前面的节点,返回时返回hair->next。并且使用pre指针指向要翻转的子链表的头节点的前驱节点(翻转子链表后,原先子链表的头节点指针begin指向翻转后的尾节点,翻转后的尾节点的next指针指向下一个待翻转子链表的头节点,翻转前的尾节点指针end,指向翻转后的头节点,但是pre指针还指向begin指针指向的节点,因此需要在翻转后,再将pre指针指向end(翻转后的头节点))

void reverseList(struct ListNode* head, struct ListNode *end){
    struct ListNode *pre = end->next, *curr = head;
    while(pre != end){
        struct ListNode *next = curr->next;
        curr->next = pre;
        pre = curr;
        curr = next;
    }
}

struct ListNode* reverseBetween(struct ListNode* head, int left, int right) {
    if(left == right){
        return head;
    }
    struct ListNode *hair = (struct ListNode*)malloc(sizeof(struct ListNode));
    hair->next = head;
    int dist = right - left + 1;
    struct ListNode* begin, *pre = hair;
    while((--left) > 0){
        pre = pre->next;
    }
    begin = pre->next;
    struct ListNode *end = begin;
    while(--dist){
        end = end->next;
    }
    reverseList(begin, end);
    pre->next = end;
    return hair->next;
}


3.力扣25K个一组翻转链表

注意:与二类似,使用hair指针和pre指针

void reverseList(struct ListNode* begin, struct ListNode* end, struct ListNode** two){
    struct ListNode *pre = end->next, *curr = begin;
    while(pre != end){
        struct ListNode *next = curr->next;
        curr->next = pre;
        pre = curr, curr = next;
    }
    two[0] = end, two[1] = begin;
}
struct ListNode* reverseKGroup(struct ListNode* head, int k) {
    struct ListNode *hair = (struct ListNode*)malloc(sizeof(struct ListNode)), *end = hair, *pre = hair;
    hair->val = 0, hair->next = head;
    while(1){
        for(int i = 0; i < k; i++){
            end = end->next;
            if(end == NULL){
                return hair->next; 
            }
        }
        struct ListNode* two[2];
        reverseList(head, end, two);
        head = two[0], end = two[1];
        pre->next = head;
        pre = end;
        head = end->next;
    }
}
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇