链表倒置

以前面试官提问我,怎样才以最小的代价将链表倒置。那时候哆哆嗦嗦半天不清。

typedef struct _NodeList
{
    struct _NodeList *pNext;
    int val;
}NodeList;
NodeList *MakeList(int num)
{
    NodeList *head,*pnow,*pnode;
    int counter;

    head = NULL;
    pnow = NULL;
    counter = 0;
    while(num>0){
        pnode = (NodeList *)malloc(sizeof(NodeList));
        pnode->val = counter++;;
        pnode->pNext = NULL;
        if(head == NULL){
            head = pnode;
            pnow = head;
        }else{
            pnow->pNext = pnode;
            pnow = pnode;
        }
        num--;
    }
    return head;
}
void ReleaseList(NodeList *head)
{
    NodeList *pnode;

    while(head != NULL){
        pnode = head;
        head = pnode->pNext;
        free(pnode);
    }
}
void PrintList(NodeList *head)
{
    while(head != NULL){
        printf("%d ",head->val);
        head = head->pNext;
    }
    printf("\n");
}
NodeList *ReverseList(NodeList *head)
{
    NodeList *pnode,*ptemp;

    if(head == NULL || head->pNext == NULL){
        return head;
    }
    pnode = head;
    head = head->pNext;
    pnode->pNext = NULL;
    while(head != NULL){
        ptemp = head;
        head = ptemp->pNext;
        ptemp->pNext = pnode;
        pnode = ptemp;
    }
    head = pnode;
    return head;
}

双向链表应该不需要倒置吧

你可能感兴趣的:(c语言)