Recerse linked list by block

本文详细介绍了如何使用块大小进行链表反转的技术,通过实例代码演示了链表节点生成、链表遍历、块反转操作及最终结果验证的过程。重点在于理解链表操作、块反转算法的实现及其实用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



//Reverse linklist in block
//eg. block size is 3 and list is
//1 2 3 4 5 6 7 8
//Output: 3 2 1 6 5 4 8 7


LNK_NODE*  ReverseByBlock(LNK_NODE* pHead ,int nBlockSize)


#include <iostream>

using namespace std;

//1 2 3 4 5 6 7 8

struct Node {
    int data;
    Node *next;
};

Node *genLink() {
    Node head;
    Node *pt = &head;
    for (int i = 1; i < 9 ; ++i) {
        pt->next = new Node;
        pt->next->data = i;
        pt->next->next = NULL;
        pt = pt->next;
    }

    return head.next;
}

void rmLink(Node *head) {
    while(head) {
        Node *t = head;
        head = head->next;
        delete t;
    }
}

void print(Node *head) {
    while (head) {
        cout<<head->data<<" ";
        head = head->next;
    }
}

Node *reverseByBlock(Node *head, int n) {
    if (n <= 1)
        return head;
    
    Node root;
    Node *tail = &root;

    
    Node *fir = head;


    while (fir) {
        Node *sec = NULL;
        int i = 0;
        Node *nextTail = fir;
        while (fir && i <n) {
            Node *t = fir;
            fir = fir->next;
            t->next = sec;
            sec = t;
            ++i;
        }

        tail->next = sec;
        tail = nextTail;
    }

    return root.next;
}

int main() {
    Node *head = genLink();
    print(head);

    cout<<endl;
    Node *rh = reverseByBlock(head,1);
    print(rh);
    rmLink(rh);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值