链表基础操作----删除偶数项后逆序
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; }
相关文章推荐
- 数据结构:链表的基本操作(创建,删除,插入,逆序,摧毁)
- 单链表的基本操作(初始化,建表,遍历,增加,删除,查找,逆序)等操作
- 【1139】数据结构上机测试2-2:单链表操作B (逆序建表+重复元素删除)
- 学习笔记——C语言实现单链表的基本操作:创建、输出、插入结点、删除结点、逆序链表
- C语言实现链表的创建、增加、删除、查询、逆序、清空等基本操作
- 日常联系:一个C++程序完成链表的增加结点、删除结点、打印、查询、逆序等操作
- c++中对单链表操作---合并两个链表&&单链表逆序&&删除链表中的中间结点
- 链表操作总结-包括链表合并、插入删除、清空复制、逆序
- 单链表的基本操作,正序/逆序建表(尾插法/头插法)、计算单链表长度、输出单链表内容、插入、删除,给出完整代码
- 头结点链表的添加结点,删除结点,链表逆序,删除指定数据等操作的实现
- HDU 5193 块状链表求带插入删除操作的全局逆序对数
- 2016年12月21日学习总结----单向循环链表操作程序(头插,尾插,中间插入,删除,逆序)
- 【1139】数据结构上机测试2-2:单链表操作B (逆序建表+重复元素删除)
- 【巩固基础】数据结构——链表的操作:链表的创建和逆序操作
- 【程序员面试宝典】数据结构基础二单链表循环链表的操作 建立|插入删除|打印|合并
- 链表的基础操作总结(链表创建,插入,删除,遍历等等)
- 链表的相关操作查找插入删除(c++ 数据结构)
- 单向链表删除操作
- 链表C++实现插入、删除元素,链表逆序
- 【程序员面试宝典】数据结构基础一单链表:创建|求长|插入|删除|排序|打印|逆置