#include<stdlib.h>
#include<malloc.h>
struct list{
int data
struct list *next
struct list *pre
}
typedef struct list node
typedef node *link
link front=NULL,rear,ptr,head=NULL
link push(int item){
link newnode=(link)malloc(sizeof(node))
newnode->data=item
if(head==NULL)
{
head=newnode
head->next=NULL
head->pre=NULL
rear=head
}
else
{
rear->next=newnode
newnode->pre=rear
newnode->next=NULL
rear=newnode
}
return head
}
void makenull(){
front=NULL
rear=NULL
}
empty(){
if(front==NULL)
return 1
else
return 0
}
int tops(){
if(empty())
return NULL
else
return rear->data
}
void pop(){
if(empty())
printf("stack is empty!\n")
else
rear=rear->pre
}
void display(link l){
link p
p=l
while(p!=NULL){
printf("%d->",p->data)
p=p->next
}
}
void main(){
int n,i
printf("input your first data!\n")
scanf("%d",&n)
front=push(n)
/*another data*/
for(i=0i<3i++)
{
printf("input:\n")
scanf("%d",&n)
push(n)
}
ptr=front
display(ptr)
printf("\n Please enter any key to pop")
pop()
ptr=front
display(ptr)
}
#include#include
#include
typedef struct Node
{
int date
struct Node * pNext
}NODE, *PNODE
//函数声明
PNODE creat_list()//创建链表
void traverse_list(PNODE pHead)//输出链表
void Insert(PNODE pHead,int pos,int e)//pos 为插入位置 e为插入的数据
void Delete(PNODE pHead,int pos,int *e)
//pos 为删除链表第pos个数 e存放被删除的数据
int main()
{
int e
PNODE pHead = NULL
pHead = creat_list()
traverse_list(pHead)
Insert(pHead,2,99)
traverse_list(pHead)
Delete(pHead,3,&e)
printf("被删除的数据为 %d\n",e)
traverse_list(pHead)
return 0
}
PNODE creat_list()
{
int len//用来存放有效结点的个数
int i
int val//用来临时存放有效结点的数据
PNODE pHead = (PNODE)malloc(sizeof(NODE))
//创建一个不存放数据的结点,pHead 为头指针
if (pHead == NULL)
{
printf("内存分配失败,程序终止!\n")
exit(-1)
}
PNODE pTail = pHead
pTail->pNext = NULL
printf("请输入你需要生成的链表的个数:len = ")
scanf("%d",&len)
for (i = 0i <leni++)
{
printf("请输入第%d个节点的值:",i+1)
scanf("%d",&val)
PNODE pNew = (PNODE)malloc(sizeof(NODE))
//当i = 0 时,创建的第一个结点是首结 每创建一个新结点
if (pNew == NULL)
{
printf("内存分配失败,程序终止!\n")
exit(-1)
}
pNew->date = val
pTail->pNext = pNew
pNew->pNext = NULL
pTail = pNew
}
return pHead
}
void traverse_list(PNODE pHead)
{
PNODE p = pHead->pNext
while(NULL != p)
{
printf("%d ",p->date)
p = p->pNext
}
printf("\n")
return
}
void Insert(PNODE pHead,int pos,int e)
{
int j = 0
PNODE p, s
p = pHead
while(p &&j <pos - 1)
{
p = p->pNext
j++
}
if(!p || j >pos - 1)
exit(-1)
s = (PNODE)malloc(sizeof(NODE))
s->date = e
s->pNext = p->pNext
p->pNext = s
}
void Delete(PNODE pHead,int pos,int *e)
{
int j = 0
PNODE p, r
p = pHead
while(p &&j <pos - 1)
{
p = p->pNext
j++
}
if(!p->pNext || j >pos - 1)
exit(-1)
r = p->pNext
p->pNext = r->pNext
*e = r->date
free(r)
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)