120 将单链表的每K个节点之间逆序
Table of Contents

ac

给定一个单链表,实现一个调整单链表的函数,使得每 K 个节点之间的值逆序,如果最后不够 K 个节点一组,则不调整最后几个节点。

5
1 2 3 4 5
3

3 2 1 4 5
# include <bits/stdc++.h>
using namespace std;

struct list_node{
    int val;
    struct list_node * next;
};

list_node * input_list()
{
    int val, n;
    scanf("%d", &n);
    list_node * phead = new list_node();
    list_node * cur_pnode = phead;
    for (int i = 1; i <= n; ++i) {
        scanf("%d", &val);
        if (i == 1) {
            cur_pnode->val = val;
            cur_pnode->next = NULL;
        }
        else {
            list_node * new_pnode = new list_node();
            new_pnode->val = val;
            new_pnode->next = NULL;
            cur_pnode->next = new_pnode;
            cur_pnode = new_pnode;
        }
    }
    return phead;
}

    //////在下面完成代码
list_node * reverse_knode(list_node * head1, int K)
{
    //////在下面完成代码
    list_node *p = head1;
    int cnt = 0;
    while(p != NULL){
        p = p->next;
        cnt ++;
    }
    list_node* pHead = new list_node();
    list_node* pTail = NULL;
    // 两个变量来判断是否有K个节点来翻转
    int sta = 1;
    int end = K;
    list_node* pLastNode = pHead;
    p = head1;
    while(sta <= cnt && end <= cnt){
        // 头插法
        for(int i=0;i<K;i++){
            list_node *pNext = p->next;
            if(pTail == NULL){
                p->next = pLastNode->next;
                pLastNode->next = p;
                pTail = p;
            }else{
                p->next = pLastNode->next;
                pLastNode->next = p;
            }
            p = pNext;
        }
        // 为下一次做准备,p已经变成下一次的开始节点了
        pLastNode = pTail;
        pTail = NULL;

        sta = end + 1;
        end = sta + K - 1;
    }
    pLastNode->next = p;
    head1 = pHead->next;
    return head1;
}

void print_list(list_node * head)
{
    while (head != NULL) {
        printf("%d ", head->val);
        head = head->next;
    }
    puts("");
}

int main ()
{
    list_node * head = input_list();
    int K;
    scanf("%d", &K);
    list_node * new_head = reverse_knode(head, K);
    print_list(new_head);
    return 0;
}