單鏈表實C語言實現

來源:互聯網
上載者:User

這是我第一次在CSDN上發部落格,這是我的處女貼哦~~~~

//List.h
#ifndef LIST_H_INCLUDED#define LIST_H_INCLUDED///與typedef的相關知識還不是很瞭解,要多加強!!typedef struct Node Node;typedef struct Node *PtrToNode;/**********此鏈表與一般的實現不一樣的地方在此,把指標隱藏起來,即typedef PtrToNode List;而常規的定義為typedef struct Node{    int data;    struct Node *next;}List;若這樣的話,初始化函數就必須用二級指標,很不方便即void ListInitia(List **list);**********************/typedef PtrToNode List;typedef PtrToNode Position;typedef int DataType;struct Node{    DataType data;    Position next;};void ListInitia(List *list);int ListInsert(List list,int index,DataType x);void ListPrint(List list);void ListDel(List *list);#endif // LIST_H_INCLUDED

//List.cpp#include<stdlib.h>#include<stdio.h>#include"List.h"/**************注意void ListInitia(List *list)的實現過程****************/void ListInitia(List *list){    *list=(List)malloc(sizeof(Node));    (*list)->data=100;    (*list)->next=NULL;}int ListInsert(List list,int index,DataType x){    List TmpList=list;    if(index<0)        return 0;    int i=0;    while((TmpList->next!=NULL)&&(index!=i))    {        i++;        TmpList=TmpList->next;    }    List NewList=(List)malloc(sizeof(Node));    NewList->data=x;    NewList->next=NULL;    TmpList->next=NewList;    return 1;}void ListPrint(List list){    List TmpList=list;    while(TmpList->next)    {        TmpList=TmpList->next;        printf("%d\t",TmpList->data);    }}//此處的實現是否正確,有沒有記憶體流失??void ListDel(List *list){    List TmpList=*list;    List tmp;    while(!TmpList->next)    {        tmp=TmpList;        TmpList=TmpList->next;        free(tmp);    }}

//測試檔案

#include <stdio.h>#include <stdlib.h>#include "List.h"int main(){    List list=NULL; //list 是一個指標    ListInitia(&list);    int i;    for(i=0;i<10;i++)        ListInsert(list,i,i+10);    ListPrint(list);    ListDel(&list);    return 0;}

以上是我個人自己寫的,不知道有沒有錯誤,如果有,歡迎指出.....

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.