链表的添加 代码
#include <stdio.h>
#include<stdlib.h>
typedef struct Node{
int data;
struct Node *next;
}node;
node * createlist()
{ int i;
node *head,*p,*s;
head = (node*)malloc(sizeof(node));
p=head ;
for(i=0;i<3;i++){
s=(node *)malloc(sizeof(node));
s->data=5-i;
p->next=s;
p=s;
}
p->next=NULL;
return head;
}
void outlist(node *head){
node *p=head->next;
while(p!=NULL)
{
printf("->%d",p->data);
p=p->next;
}
}
// 添加函数
void insert(node *head,int key,int d){
node *q,*p=head->next;
node *s=(node *)malloc(sizeof(node));
s->data=d;
while(p!=NULL&&p->data!=key){
q=p;
p=p->next;
}
if(p==NULL){ //没有找到要插入的位置 就放到最后
p->next=s;
s->next=NULL ;
}
else{
q->next=s;
s->next=p;
}
}
int main() {
int d=33;
node *head=createlist();
outlist(head);
insert(head,5,d);
printf("\n");
outlist(head);
return 0;
}
简单一点就是有两个指针 一个指针指向要插入位置的前一个结构体 一个指向后一个结构体
然后前一个的指针域指向要插入的那个结构体 要插入那个结构体的指针域指向后一个的指针
这样就连起来了
小白一枚 有错的希望能给我指出来哦 谢谢啦(=^ ^=)
又学了链表的删除
函数如下
void deletenode(node *head,int key){
//node *p,*q;
//p=head->next;
//q=head;
//while (p!=NULL&&p->data!=key){
// q=p;
// p=p->next;
//}
node *q,*p=head->next; //前面与insert函数类似
while(p!=NULL&&p->data!=key){
q=p;
p=p->next;}
q->next=p->next;
free (p);
}
大概意思就是先把要删掉的指针指向的结点给前一个指针域
再把要删掉的free掉
又学了排序
学过选择排序的应该一看就懂了吧
void paixu(node *head)
{
node *p,*q;
int t;
p=head->next;
while(p!=NULL)
{
q=p->next;
while(q!=NULL){
//遍历p后面所有结点
if(p->data>q->data){
t=p->data;
p->data=q->data;
q->data=t;
}
q=q->next;
}
p=p->next;
}
}