1. 程式人生 > 實用技巧 >單鏈表基本操作

單鏈表基本操作

單鏈表基本操作

複習資料結構時手撕的單鏈表基本操作,我覺得需要注意的地方,我都寫在了註釋裡了。


#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#define inf 0x3f3f3f
using namespace std;
typedef struct node{
    int x,y;
    node *next;
}NODE;
NODE* head_insert(NODE * head,int x,int y){
    NODE *s;
    s = (NODE *)malloc(sizeof(NODE));//申請空間
    s->x = x;
    s->y = y;
    s->next = head->next;//將新節點下一個指向頭結點的下一個
    head->next = s;//將頭結點與新節點連線起來
    return head;//返回並賦值給頭結點,改變頭結點地址值

}
NODE* tail_insert(NODE * tail,int x,int y){
    NODE * s;
    s = (NODE *) malloc(sizeof(NODE));
    s->y = y;
    s->x = x;
    s->next = NULL;
    tail->next = s;//尾結點的下一個指向新節點
    tail = s;//令尾結點移動到新節點出
    return tail;//返回並賦值給尾結點,改變尾結點地址值
}
void for_each(NODE *head){
    NODE *s;
    int i=0;
    s = head->next;
    while(s){
        cout<<s->x<<" "<<s->y<<" i="<<i++<<endl;
        s = s->next;
    }

}
void query_by_index(NODE * head,int k){
    NODE *s;
    s = (NODE *)malloc(sizeof(NODE));
    s = head;
    for(int i=1;s&&i<=k;i++){
        s = s->next;
    }
    cout<<s->x<<" "<<s->y<<endl;
}
void query_by_value(NODE * head,int v,int u){
    NODE *s;
    s = (NODE *)malloc(sizeof(NODE));
    s = head;
    int i=1;
    while(s){
        s = s->next;
        if(s->x == v&&s->y==u){
            cout<<s->x<<" query "<<s->y<<" i="<<i<<endl;
            break;
        }
        i++;
    }
}
void insert_in_someNODE(NODE * head,int k,int x,int y){
    NODE *s,*ns;
    s = (NODE *)malloc(sizeof(NODE));
    s = head;
    int i;
    for(i=1;s&&i<=k;i++){
        s = s->next;
    }
    if(i<=k)
        cout<<-1<<endl;
    else{
        ns = (NODE *)malloc(sizeof(NODE));
        ns->x = x;
        ns->y = y;
        ns->next = s->next;
        s->next = ns;
    }
}
void delete_in_someNODE(NODE * head,int k){
    NODE *s,*q;
    s = (NODE *)malloc(sizeof(NODE));
    s = head;
    int i;
    for(i=1;s&&i<=k;i++){
        s = s->next;
    }
    q = s->next;
    s->next = q->next;
    free(q);
}
int get_Len(NODE * head){
   int len=0;
   NODE *s;
   s = head->next;
//    int i=1;
   while(s){
       s = s->next;
       len++;
   }
   return len; 
}
int main(){
    NODE *spot_set,*tail,*thead;
    //頭插
    spot_set = (NODE*)malloc(sizeof(NODE));
    spot_set->next = NULL;
    spot_set = head_insert(spot_set,10,10);
    spot_set = head_insert(spot_set,1,1);
    for_each(spot_set);
    //有頭結點 尾插
    tail = (NODE*)malloc(sizeof(NODE));
    thead = (NODE*)malloc(sizeof(NODE));
    tail->next = NULL;
    thead = tail;
    tail = tail_insert(tail,1,2);
    tail = tail_insert(tail,2,3);
    for_each(thead);


    //按序號查詢
    query_by_index(spot_set,2);
    //按值查詢(從頭結點開始第一個)
    query_by_value(spot_set,1,1);
    //在某個位置插入新節點
    insert_in_someNODE(thead,0,9,9);
    for_each(thead);
    //在某個位置刪除節點
    delete_in_someNODE(thead,0);
    for_each(thead);
    //計算連結串列長度
    cout<<get_Len(thead)<<endl;
    free(spot_set);
    free(tail);
    free(thead);
    return 0;
}
如有錯漏,歡迎指正。