1. 程式人生 > >動態連結串列的建立及使用

動態連結串列的建立及使用

連結串列的建立及使用一直是一個小難題,今天我分享一下我的學習心得吧。
首先,要建立一個頭結點。
struct node
{
int data;
struct node *next;
};

完成後分為4步:1、建立連結串列 2、輸出連結串列 3、插入某一個數 4、刪除某一個數
這就是一個簡單鏈表的結構,當然,如果你想新增更多功能的話,可以自己加入,是它變得更加豐富多彩!
1、建立連結串列

SLIST *creat_slist(void);//建立連結串列
SLIST *creat_slist(void)
{
    int c;
    SLIST *h,*s
,*r; h=(SLIST *)malloc(sizeof(SLIST)); r=h; scanf("%d",&c); while(c!=-1) { s=(SLIST *)malloc(sizeof(SLIST)); s->data=c; r->next=s; r=s; scanf("%d",&c); } r->next='\0'; return h; }

2、輸出連結串列

void printf_slist(SLIST *h
);//輸出連結串列 void printf_slist(SLIST *h) { SLIST *p; p=h->next; if(p=='\0') printf("Linklist is null!\n"); else { printf("head"); do { printf("->%d",p->data); p=p->next; } while
(p!='\0'); printf("end\n"); } }

3、插入某一個數

void insert_slist(SLIST *h,int x,int y);//插入某一個數
void insert_slist(SLIST *h,int x,int y)
{
    SLIST *s,*p,*q;
    s=(SLIST *)malloc(sizeof(SLIST));
    s->data=y;
    q=h;
    p=h->next;
    while(p!='\0'&&p->data!=x)
    {
        q=p;
        p=p->next;
    }
    s->next=p;
    q->next=s;

}

4、刪除某一個數

void delete_slist(SLIST *h,int x);//刪除某一個數
void delete_slist(SLIST *h,int x)
{
    SLIST *p,*q;
    q=h;
    p=h->next;
    while(p!='\0'&&p->data!=x)
    {
        q=p;
        p=p->next;
    }
    if(q->data==x)
    {
        q->next=p->next;
    }
}

5、主函式

int main(void)
{
    SLIST *h;
    int x,y,m;
    system("cls");
    scanf("%d%d",&x,&y);//y插入到x的前面
    scanf("%d",&m);//刪除m
    h=creat_slist();
    printf_slist(h);
    insert_slist(h,x,y);
    printf_slist(h);
    delete_slist(h,m);
    printf_slist(h);
}