链表的定义
链表是一种常见的重要的数据结构。它是动态地进行存储分配的一种结构。它可以根据需要开辟内存单元。链表有一个“头指针”变量,以head表示,它存放一个地址。该地址指向一个元素。链表中每一个元素称为“结点”,每个结点都应包括两个部分:一为用户需要用的实际数据,二为下一个结点的地址。因此,head指向第一个元素:第一个元素又指向第二个元素;……,直到最后一个元素,该元素不再指向其它元素,它称为“表尾”,它的地址部分放一个“NULL”(表示“空地址”),链表到此结束。
结构体形式
struct test
{int data;struct test *next;
};
链表的插入
(1)头插法
struct Test *insertfromhead(struct Test *head)
{struct Test *new = NULL;while(1){new =( struct Test *)malloc(sizeof(struct Test));printf("please input new node(0 qiut)!\n");scanf("%d",&new->data);if(new->data == 0){printf("quit\n");return head; }else if(head == NULL){head = new;}else{new->next = head;head=new;}}return head;
}
(2)尾插法
struct Test *insertfromtail(struct Test *head)
{struct Test *new = NULL;struct Test *p = head;while(1){new = (struct Test *)malloc(sizeof(struct Test));printf("please input new node(0 quit)!\n");scanf("%d",&new->data);if(new->data == 0){printf("quit\n");return head; }if(p == NULL){p = new;head = p; }else if{while(p->next != NULL){p = p->next; }p->next = new;}}return head;}
(3)在指定节点前插
struct Test *insertfrombefore(struct Test *head,int insert_data,struct Test *new)
{struct Test *p = head;if(p->data == insert_data){new->next = head;return new;}//遍历while(p->next != NULL){if(p->next->data == insert_data){new->next = p->next;p->next=new;return head;}p = p->next;}printf("no this data %d\n",insert_data);return head;}
head:链表头节点
insert_data :被前插节点的值
new:新节点
(4)在指定节点后插
struct Test *insertfrombehind(struct Test *head,int insert_data,struct Test *new)
{struct Test *p = head;while(p != NULL){if(p->data == insert_data){new->next = p->next;p->next = new;return head;}p = p->next;}printf("no this data %d\n",insert_data);return head;}
head:链表头节点
insert_data :被后插节点的值
new:新节点
链表固定节点的删除
struct test *delelink(struct test*head,int data)
{struct test*p=head;if(p->data==data){head=head->next;// free(p);一般只有malloc开辟的空间才能被freereturn head;}while(p->next!=NULL){if(p->next->data==data){p->next=p->next->next;return head;}p=p->next;}return head;
}
data:要删除节点的data值
链表的查找
int searchlink(struct test* head,int data){while(head!=NULL){if(head->data==data){return 1;}head=head->next;}
}
链表节点的计算
int getlinknumbr(struct test* head)
{int cnt=0;while(head!=NULL){cnt++;head=head->next;}return cnt;
}
链表的打印
void printLink(struct test *head)
{struct test *point;point=head;while(point!=NULL){printf("%d ",point->data);point=point->next;}putchar('\n');
}
链表空间的释放
void FreeSpace(struct Text *head){struct Text *p;while(head!=NULL){p=head->next;free(head);head=p;}