单链表///
//定义节点
struct node
{
int data;
struct node *next;
};
typedef struct node NODE;
//申请节点并赋值
NODE *ApplyNODE(int x)
{
NODE *p;
p=(NODE *)malloc(sizeof(NODE));
p->data=x;
p->next=NULL;
return (p);
}
//初始化链表
NODE *InitList()
{
NODE *head;
head=(NODE *)malloc(sizeof(NODE));
head->next=NULL;
return (head);
}
//将节点插入到链表
//(1)将节点p插入到链表头(p作为head之后的第一个元素,成为了新的表头节点)
p->next=head->next;
head->next=p;
//(2)将节点p插入到指定节点q之后
p->next=q->next;
q->next=p;
//(3)将节点p插入到链表尾
先找到链表的尾节点q:
NODE *Searchrear(NODE *head)
{
NODE *q;
q=head;
while(q->next != NULL)
{
q=q->next;
}
return (q);
}
再将p节点插入到指定节点q的后面即可!
//头插法建立链表
NODE *CreateFromHead()
{
NODE *head, *p, *q;
int i, n, x;
printf("\nInput the length of the line:");
scanf("%d", &n);
head=InitList();
printf("\nInput %d datas:", n);
for(i=0; i<n; i++)
{
scanf("%d", &x);
p=applyNODE(x);
p->next=head->next;
head->next=p;
}
return (head);
}
//尾插法建立链表
NODE *CreatFromTail()
{
NODE *head, *p, *q;
int i, n, x;
printf("\nInput the length of the line :");
scanf("%d", &n);
head=q=InitList();
printf("\nInput %d datas:", n);
for(i=0; i<n; i++)
{
scanf("%d", &x);
p=applyNODE(x);
q->next=p;
q=p;
}
return (head);
}
//删除节点
//(1)删除给定节点p的后继节点, 用q记录要删除的节点
q=p->next;
p->next=q->next;
free(q);
//(2)删除给定节点p
NODE *deletenode(NODE *head, NODE *p)
{
NODE *q;
q=head;
while(q->next != p)
{
q=q->next;
}
q->next=p->next;
free(p);
return (head);
}
//输出单链表
void Display(NODE *head)
{
NODE *p;
printf("\nThe line are:");
p=head->next;
while(p != NULL)
{
printf("%d ", p->data);
p=p->next;
}
}
//查找给定值节点
NODE *Search(NODE *head, int x)
{
NODE *p;
p=head->next;
while(p != NULL)&&(p->data != x)
{
p=p->next;
}
return (p);
}
链表实现栈///
//栈节点
struct node
{
int data;
struct node *next;
};
typedef struct node StackNode;
StackNode *top;
//初始化栈
StackNode *InitStack()
{
NODE *top;
top=(StackNode *)malloc(sizeof(StackNode));
top->next=NULL;
return (top);
}
//将x进栈
StackNode *Push(StackNode *top, DataType x)
{
StackNode *p;
p=(StackNode *)malloc(sizeof(StackNode));
p->data=x;
p->next=top->next;
top->next=p;
return (top);
}
//将栈顶元素出栈
StackNode *Pop(StackNode *top)
{
StackNode *p;
if(top->next == NULL)
{
printf(" 栈空,无法出栈");
return(top);
}
p=top->next;
top->next=p->next;
free(p);
return (top);
}
链表实现队列///
//链队列节点
struct node
{
int data;
struct node *next;
};
typedef struct node QueueNode;
struct node2
{
QueueNode *front;
QueueNode *rear;
};
typedef struct node2 Queue;
//初始化队列
Queue InitQueue()
{
Queue Q;
Q.front=(QueueNode *)malloc(sizeof(QueueNode));
Q.front->next=NULL;
Q.rear=Q.front;
return (Q);
}
//x进队列
Queue InsertQ(Queue Q, int x)
{
QueueNode *p;
p=(QueueNode *)malloc(sizeof(QueueNode));
p->data=x;
p->next=NULL;
Q.rear->next=p;
Q.rear=p;
return (Q);
}
//出队列
Queue DeleteQ(Queue Q)
{
QueueNode *p;
if(Q.front == Q.rear)
{
printf("队列空,无法出队列!");
return (Q);
}
p=Q.front->next;
Q.front->next=p->next;
if(p==Q.rear)
{
Q.rear=Q.front;
}
free(p);
return (Q);
}
链表操作
最新推荐文章于 2023-01-24 16:48:30 发布