C++面试准备之单链表操作

C++面试准备之单链表操作

链表节点定义

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

创建链表

ListNode* createList(int n) {//参数为链表的节点数目
    ListNode *pHead,*s;
    pHead = NULL;
    for(int i=0;i*r = (ListNode*)malloc(sizeof(ListNode));
        r->data = i;
        r->next = NULL;
        if(pHead == NULL) pHead = r;
        else s->next = r;
        s = r;
    }
    return pHead;
}

打印链表

void printList(ListNode* pHead) {
    ListNode* t = pHead;
    while(t) {
        cout << t->data << " ";
        t = t->next;
    }
}

链表反转

ListNode* reList(ListNode* pHead) {
    ListNode *reHead = NULL;
    ListNode *pre = NULL;
    ListNode *cur = pHead;
    while(cur) {
        ListNode* next = cur->next;
        if(next == NULL) reHead = next;
        cur->next = pre;
        pre = cur;
        cur = next;
    }
    return reHead;
}

链表去重

ListNode* deleteNode(ListNode* pHead) {
    ListNode *p,*q,*r;
    p = pHead->next;
    while(p) {
        r = p;
        while(r->next) {
            if(r->next->data == p->data) {
                q = r->next;
                p->next = q->next;
                free(q);
            }else{
                r = r->next;
            }
        }
        p = p->next;
    }
    return pHead;
}

从尾部开始打印链表

用栈从尾部开始打印

void printListReverseWithStack(ListNode* pHead) {
    stack nodes;
    ListNode* pNode = pHead;
    while(pNode) {
        nodes.push(pNode);
        pNode = pNode->next;
    }
    while(!nodes.empty()) {
        pNode = nodes.top();
        cout << pNode->data << " ";
        nodes.pop();
    }
}

递归从尾部开始打印

void printListReverseWithRecursion(ListNode* pHead) {
    if(phead) {
        if(pHead->next) {
            printListReverseWithRecursion(pHead->next);
        }
        cout << pHead->data << " ";
    }
}

你可能感兴趣的:(C++面试准备之单链表操作)