《数据结构与算法分析(c语言版)》学习笔记①链表

xiaoxiao2021-02-28  41

链表相关函数(指针法): 链表的建立: #inlucde<stdio.h> #include<stdlib.h> #define LEN sizeof(NODE) typedef struct NODE { int elem; struct NODE* next }NODE; NODE * creat() { NODE * head,*P1,*P2; int n=0,i=0; printf("how manny linked list do you want to creat?\n"); scanf("%d",&n); for(i;i<n;i++)//用p2来存放新的链表 { if(i==0) {head=p1=p2=(NODE*)malloc(LEN);} else {p1=p2;*p1.next=p2=(NODE*)malloc(LEN);} if(i==n)*p2.next=NULL; printf("请输入第%d个elem的值\n",i+1);scanf("%d",&p2.elem); } } 判断链表是否是空链表: int isempty() { return head==NULL; }

判断链表是否为末尾:

int IsLast(NODE*p)//p为前驱元的next 。 {  return *p.next==NULL;  } //0为非末尾,1为末尾。

寻找链表中的某一个元素: NODE*find(int x,NODE*head)//读入需要的寻找的元素,和链表的头指针。 { NODE*p; p=head; for(;*p.next!=NULL&&*p.elem!=x;) p=*p.next; return p; } //返回找到的元素的地址 删除某一个特定的链表(给定链表的前驱元的地址): #include<stdlib.h>//需要包含stdlib头文件。 void Delete(NODE*p)//给定需要删除的链表前驱元的地址(如未给定可用find函数的变体). { NODE*temp; temp=*p.next; *p.next=temp.next; free(temp); } 插入某一个链表:

void insert(NODE*p)//此处插入前面(依旧是用find的变体函数寻找)(题目中要注意插入的位置) NODE*new_struct; new_struct=(NODE*)malloc(LEN); scanf("%d",&(*new_struct.elem)) *new_struct.next=*p.next; *p.next=new_struct; }删除整个表的方法: void delete_list(NODE*head)//free函数必须是需要释放的结构体的地址。 { NODE*p=head; head=NULL; while(*p.next!=NULL); { NODE*temp; temp=*p.next; free(p); p=temp; } free(p);//末尾因为.next是null所以不执行,需要单独释放。 }
转载请注明原文地址: https://www.6miu.com/read-2625839.html

最新回复(0)