顺序表与链表
单链表
线性表中的数据结点在内存中的位置是任意的,即逻辑上是线性的数据元素在物理位置(内存存储的位置)上不一定相邻。
-
遍历链表
void printlink(struct Test *head)//链表头 { while(head != NULL){//直到链表尾指向NULL结束 printf("%d ",head->data); head = head->next; } putchar('\n'); }
-
计算链表节点个数
int getLinkNodeNumber(struct Test *head) { int cnt = 0; while(head != NULL){ cnt++; head = head->next; } return cnt; }
-
查询链表的数据
int findData(struct Test *head,int data) { while(head != NULL){ if(head->data == data){ return 1; } head = head->next; } return 0; } if(findData(&t1,1)){ printf("have 1\n"); }else{ printf("no 1\n"); }
-
链表从指定节点后方插入新节点
/* 1.如果链表只有一个节点,直接查到后面 2.查找Data,找到后先让new->next = p->next;再进行p->next =new; */ int insertFromBehind(struct Test *head,int data,struct Test *new) { struct Test* p = head; if(p->next == NULL){ p->next = new; }else{ while(p->next != NULL){ if(p->data == data){ new->next = p->next; p->next = new; } p = p->next; } } return 0; }
-
链表从指定节点前面插入新节点
//后插不改变头,前插可能改变了头,所以前插返回一个头 //1.在链表头之前插入,返回新头 //2.查找Data,找到后先让new->next = p->next;再进行p->next =new;返回头 struct Test* insertFromForward(struct Test *head,int data,struct Test *new) { struct Test *p = head; if(p->data == data){ new->next = p; puts("insert ok"); return new; } while(p->next != NULL){ if(p->next->data == data){ new->next = p->next; p->next = new; printf("insert ok\n"); return head; } p = p->next; } printf("intsert fail\n"); return head; }
-
删除节点
//删除第一个节点会改头。 struct Test * delNode(struct Test *head,int data) { struct Test * p = head; if(p->data == data){ head = p->next; return head; } while(p->next != NULL) { if(p->next->data == data){ //struct Test *tmp = p; p->next = p->next->next; //free(p);//如果是动态创建链表(malloc),需要free return head; } p = p->next; } printf("no this data\n"); return head; }
-
头插创建链表
struct Test * head_insert_node(struct Test *head,struct Test *new)//头插法 { if(head == NULL){ head = new;//如果是第一个节点 }else{ new->next = head;//不是则头插 head = new; } return head; } struct Test * create_link(struct Test *head)//创建链表 { while(1){ struct Test *new = (struct Test *)malloc(sizeof(struct Test));//创建新节点并开辟空间 printf("please input new data:\n"); scanf("%d",&(new->data));//输入节点的Data数据 if(new->data == 0){//输入的是0则停止创建 printf("0 quit\n"); free(new);//free掉存放0数据这个节点 return head; }else{ head = head_insert_node(head,new);//头插 } } }
-
尾插法
struct Test * tail_insert_node(struct Test * head,struct Test *new) { struct Test * p = head; if(p == NULL){//如果是空链表 head = new; return head; } while(p->next != NULL){//尾插 p = p->next; } p->next = new; return head; }