108 反转部分单向链表
Table of Contents

ac

# include <bits/stdc++.h>
using namespace std;

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

list_node * input_list(void)
{
    int n, val;
    list_node * phead = new list_node();
    list_node * cur_pnode = phead;
    scanf("%d", &n);
    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_list(list_node * head, int L, int R)
{
    //////在下面完成代码
    if(L == R){
        return head;
    }
    // L 之前的
    list_node *pPre = NULL;
    list_node *pStart = NULL;
    int LTmp = L;
    if(L > 1){
        pStart = head;
        while(--L > 0){
            pPre = pStart;
            pStart = pStart->next;
        }
    }else{
        pStart = head;
    }
    // pHead 头插法存储逆序的
    list_node *pHead = new list_node();
    list_node *pTail = NULL;
    list_node *p = pStart;
    int cnt = R - LTmp + 1;
    for(int i=0;i<cnt;i++){
        list_node *pNext = p->next;
        if(pTail == NULL){
            p->next = pHead->next;
            pHead->next = p;
            pTail = pHead->next;
        }else{
            p->next = pHead->next;
            pHead->next = p;
        }
        p = pNext;
    }
    pTail->next = p;
    if(pPre == NULL){
        pPre = pHead->next;
        delete pHead;
        return pPre;
    }else{
        pPre->next = pHead->next;
        delete pHead;
        return head;
    }
}

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


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