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

#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);
    }
    return 0;
}



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值