1. 程式人生 > >C++_連結串列的基本操作

C++_連結串列的基本操作

/*
 * 連結串列相對於陣列:
 * 插入和刪除的效率高;
 * 查詢效率低;
 * 儲存額外的節點指標,帶來空間上的消耗;
 */
#include <iostream>
using namespace std;
//定義連結串列的資料結構
struct ListNode{
    int val;
    struct ListNode *next;
    ListNode(int x): val(x), next(NULL){}
};

//建立單向連結串列
ListNode* list_Create(){
    ListNode* pHead, *pCurrent, *pNew;
    int data;
    pHead = new ListNode(0);
    pCurrent = pHead;
    cin>>data;
    while(data != -1){
        pNew = new ListNode(data);
        pCurrent->next = pNew;
        pCurrent = pNew;
        cin>>data;
    }
    return pHead->next;
}
// 列印單向連結串列
void list_Print(ListNode* pHead){
    if(pHead == NULL) return ;
    ListNode* tmp = pHead;
    while(tmp){
        cout<<tmp->val<<"  ";
        tmp = tmp->next;
    }
    cout<<endl;
}
//插入,值x後插入y
ListNode *list_Insert(ListNode* pHead, int x, int y){
    if(pHead == NULL) return NULL;
    ListNode *pCurrent, *pNew;
    pCurrent = pHead;
    pNew = new ListNode(y);
    while(pCurrent){
        if(pCurrent->val == x) break;
        pCurrent = pCurrent->next;
    }
    if(pCurrent == NULL){
        cout<<"未找到值為:"<<x<<endl;
    }
    else{
        pNew->next = pCurrent->next;
        pCurrent->next = pNew;
    }
    return pHead;
}
//刪除
ListNode* list_Delete(ListNode* pHead, int data){
    if(pHead == NULL) return NULL;
    ListNode* pPre, *pCurrent;
    pPre = pHead;
    pCurrent = pPre->next;
    // 刪除頭節點
    if(pHead->val == data){
        delete pHead;
        return pCurrent;
    }
    while(pCurrent){
        if(pCurrent->val == data) break;
        pPre = pCurrent;
        pCurrent = pCurrent->next;
    }
    if(pCurrent == NULL){
        cout<<"未找到值為:"<<data<<"節點"<<endl;
    }
    else{
        pPre->next = pCurrent->next;
        delete pCurrent;
    }
    return pHead;
}
//銷燬單向連結串列
int list_Destory(ListNode* pHead){
    if(pHead == NULL) return 0;
    ListNode *t = NULL;
    while(pHead){
        t = pHead->next;
        delete pHead;
        pHead = t;
    }
    return 0;
}
int main(){
    ListNode* node = list_Create();
    list_Print(node);
    int x, y;
    //cin>>x>>y;
    //list_Print(list_Insert(node, x, y));
    cin>>x;
    list_Print(list_Delete(node, x));

    return 0;
}