您的位置:首页 > 其它

链表基础操作----删除偶数项后逆序

2016-10-24 16:23 501 查看
#include<iostream>
#include<cstdio>
#include<malloc.h>
#include<cstdlib>
#define LEN sizeof(node)
using namespace std;
struct node
{
int data;
node  *next;
}head;
struct node*creat()   //建立一个单链表
{   int i=0;
struct node *p1,*p2,*head;
p1=p2=(struct node*)malloc(LEN);
while(scanf("%d",&p1->data)&&(p1->data!=0))  //0作为结束标志
{
if(i==0)
{
i=1;
head=p1;
}
else
{
p2->next=p1;
}
p2=p1;
p1=(struct node*)malloc(LEN);
}
p2->next=NULL;
return head;
}
void print(struct node*head)  //输出一个链表
{
while(head!=NULL)
{
printf("%d ",head->data);
head=head->next;
}
}
int de(struct node *head)    //删除链表偶数项
{     int i=0;
struct node *d;
while(head->next!=NULL)
{     if(head->next->next==NULL)   //这里是一个队尾部判断,防止删除尾部 其他的地方都很好理解
{
delete head->next;          //deleta可以删除普通的malloc开的空间,但是new还可以给类开空间这时候用free就不匹配了
head->next=NULL;
break;
}
d=head->next->next;
delete head->next;
head->next=d;
head=head->next;
}
}
struct node* ni(struct node*head )  //头插法逆序单链表
{
struct node* newhead,*t;      //t工作指针
newhead=(struct node*)malloc(LEN);
newhead=NULL;
while(head!=NULL)
{
t=head->next;
head->next=newhead;
newhead=head;
head=t;
}

 return newhead;
}

int main()
{
printf("输入一组链表,0结束\n");
struct node*a=creat();
de(a);
struct node*b=ni(a);
printf("链表删除偶数元素后逆序结果为");
print(b);

return 0;
}


链表的建立和简单的操作,for循环建标和查找

#include <stdio.h>
#include <stdlib.h>
struct link
{
int data;
struct link *next;
};

//程序填空----请按题目要求完成函数功能。
struct link * search(struct link *head,int x)
{
head=head->next;
while(head)
{
if(head->data==x)
{
return head;
}
else if(head->next!=NULL)
head=head->next;
else return NULL;
}
}
int main()
{
struct link *head,*p,*q;
int n,i,x;
while(scanf("%d",&n)!=-1)   //n是长度
{
head=q=(struct link *)malloc(sizeof(struct link));
if(head!=NULL)
{
head->next=NULL;
for(int i=0;i<n;i++)
{   p=(link*)malloc(sizeof(struct link));  //p是活动指针
scanf("%d",&(p->data));
q->next=p;
q=p;
}
q->next=NULL;
}

//读入检索条件
scanf("%d",&x);

p=search(head,x);
//输出
if(p!=NULL)
printf("%d\n",p->data);
else
printf("%d\n",0);
free(head);
}

4000
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐