读书人

IT公司面试题收集整理-数据结构有关复

发布时间: 2013-03-12 11:19:35 作者: rapoo

IT公司面试题收集整理---数据结构相关复习---各种链表的各种操作
事先声明:

由于这些链表的操作涉及到数据结构,所以很多函数的细节,我并没有亲自验证,有兴趣的同学可以给我提出宝贵的意见,在下不胜感激。

我感觉数据结构最终要的是思想。好了废话不多说了,上代码喽。。

单链表的增删改查

#include<stdio.h>//双向链表的建立,插入,删除操作typedef struct student{int data;struct student *pre;struct student *next;}node;//创建双向链表node create(){node *head,*p,*s;int x,cycle=1;head=(node *)malloc(sizeof(node));p=head;while(cycle){printf("\n请输入数据data:");scanf("%d",&x);if(x==0){cycle=0;break;}s=(node *)malloc(sizeof(node));s->data=x;p->next=s;s->pre=p;p=s;}head=head->next;head->pre=NULL;p->next=NULL;return head;}//双向链表插入节点node *insert(node *head,int data){node *x,*p;//x是要插入的节点p=head;//此处head笔者代表头结点x=(node *)malloc(sizeof(node));x->data=data;while(p->next->data<x->data&&p->next!=NULL){p=p->next;}if(p->next==NULL){x->next=p->next;//顺序连接p->next=x;x->next=p;//逆序连接x->pre=NULL;}else{x->next=p->next;//顺序连接p->next=x;x->pre=p;//逆序连接x->next->pre=x;}return head;}//双向链表的删除node *deleteNode(node *head,int data){node *p1,*p2;p1=head;//此处head笔者不代表头结点,代表第一个节点while(p1!=NULL&&p1->data!=data){p1=p1->next;}if(p1->data==data)//如果因为数据找到跳出循环,//需要注意:里面可能还会出现首位节点的特殊情况,我们就不做讨论了。//实际上因为head代表第一个节点而非头结点,实际上下面的代码也是正确的,// 但是为了更加的精确,尽量分情况写出,我们这里就不讨论了。{p1->pre->next=p1->next;p1->next->pre=p1->pre;free(p1);}else//(p1->next==NULL)//如果因为循环到底没找到,那么说明没有这个值{printf("不存在这个节点!!!");}}



读书人网 >编程

热点推荐