最近看了数据结构,打算写一个小的总结,后续一系列的,慢慢都会有,把自己写过的代码记录一下,也督促自己不要半途而废,就酱~
一 线性链表
单链表大家都很熟,直接上代码:(参考pointers on C 一书di12章)
while ((current=*linkP)!=NULL &&
current->value < new_valu其中部分涉及指针的指针,比较蛋疼,说一下
假如有这样的表达式:int a = 12;int *b = &a; int **c = &b;
那么就有:
表达式 相当的表达式
a 12
b &a
*b a, 12
c &b
*c b,&a
**c *b, a, 12
在while循环中我用到了
while ((current=*linkP)!=NULL &&
current->value < new_value)
{
linkP=¤t->link;
}
current=*linkP这个句子,*linkP相当于下一个node的地址,所以这是让current指向了linkP当前指向节点的下一个节点,current 是指向当前节点的指针,linkP是指向当前节点的link字段的指针或者指向头指针的指针,程序有任何错误,可以在评论里告知,另,优快云编辑格式为什么在插入代码后切不回文字模式了?
#include <STDIO.H> #include <stdlib.h> typedef struct Node { struct Node *link; int value; }Node; #define FALSE 0 #define TRUE 1 int InsertAll( Node** linkP,int new_value) { Node *current; Node *new1; //寻找插入的位置 while ((current=*linkP)!=NULL && current->value < new_value) { linkP=¤tt->link; } new1 =(Node*)malloc(sizeof(Node)); if( new1==NULL) { return FALSE; } new1->value=new_value; new1->link = current; *linkP = new1; return TRUE; } int deleteAll(Node** link,int value) { Node *current; while ((current=*link)!=NULL && current->value != value) { link=¤tt->link; } *link=current->link; free(current); return 0; } int GetElem_Value(Node* link,int value) { int i=1; while((link)!=NULL) { if (link->value==value) { printf("find! %d\n",i); return 0; } ++i; link=link->link; } printf("ERROR:don not find \n"); return -1; } int GetElem_Int(Node* link,int position) { int i=1; while((link)!=NULL) { if (i==position) { printf("find! %d %d\n",i,link->value); return 0; } ++i; link=link->link; } printf("ERROR:don not find \n"); return -1; } int PrintLinklist(Node* link) { while ((link)!=NULL) { printf("%d\n",link->value); link=link->link; } return 0; } int main() { Node **linklist; Node *link; Node first; first.link=NULL; first.value=3; link=&first; linklist=&link; InsertAll(linklist,10); PrintLinklist(link); // GetElem_Value(link,10); //GetElem_Int(link,1); //GetElem_Int(link,2); //GetElem_Int(link,3); deleteAll(linklist,10); PrintLinklist(link); return 0;
}