C語言鍊錶的建立 插入 查詢 刪除 清空操作

2021-05-27 09:59:34 字數 1856 閱讀 3494

#include "list.h"

#include

#include

#include

//建立頭結點

node* create_phead()

node *phead=(node*)malloc(sizeof(node));

phead->next=null;

return phead;

//在末尾新增乙個元素

void add_node(node* phead,int d)

node* p=(node*)malloc(sizeof(node));

p->data=d;

p->next=null;

node*q=phead;

while(q->next!=null)

q=q->next;

q->next=p;

//getdata –查詢第n個元素的值

int getdata(node *phead,int n)

int i=0;

if(n<1) return 0;

node *p=phead;

while(p->next!=null&&i++i;

p=p->next;

//      printf("%d-%d\n",i,p->data);

return p->data;

//getbyindex –查詢第n個結點

node* getbyindex(node *phead,int n)

int i=0;

if(n<1) return phead;

node *p=phead;

while(p->next!=null&&i++i;

p=p->next;

return p;

//getposition –查詢元素d的位置,如果成功返回d的位置,不成功返回-1

int getpos(node *phead,int d)

node *p=phead;

int i=0;

while(p->next!=null)

++i;

p=p->next;

if(d==p->data)

return i;

return -1;

//輸出鍊錶元素

void print(node* phead)

node* q=phead;

while(q->next!=null)

q=q->next;

printf("%d\n",q->data);

//移除第n個結點

void del_node(node *phead,int n)

/*     node *prev;

node *q=phead;

int i=0;

while(q->next!=null&&i++i;

prev=q;

q=q->next;

prev->next=q->next;

free(q);

q=null;

node* prev=getbyindex(phead,n-1);

node* find=getbyindex(phead,n);

prev->next=find->next;

free(find);

find=null;      

//鍊錶清空

void clear(node *phead)

node *q=null;

while(phead!=null)

q=phead->next;

phead->next=null;

free(phead);

phead=q;

鍊錶 建立 插入 刪除 查詢

include include typedef struct node int data struct node next node node createlist 建立乙個單鏈表 printf 建立乙個長度為 n的鍊錶,請輸入 n int n scanf d n node l l node mal...

鍊錶基本操作(建立,插入,查詢,刪除) C語言

工具 xcode main.c node include include typedef struct studentstu pragma mark 鍊錶的建立 if0 頭插入法建表 stu creat linklist int n else return head else 尾插入建表 stu c...

C語言鍊錶的插入和刪除 建立

choicetxt.h 執行要重複的 選擇執行的醒目並將結果付給choice include stdio.h int choicetxt int choice else creat.c include stdio.h include stdlib.h include define.h extern ...