单链表的设计与实现

来源:互联网 发布:淘宝达人机构合作 编辑:程序博客网 时间:2024/06/05 04:27

现在在学数据结构,开始把自己的代码贴出来交流一下

第一章    线性表

其实线性表很简单的,但是我开始写代码的时候还是感觉很痛苦。学习过程中感觉最重要的就是知道了头结点的应用。自从有了它,再也不用分类了。。大笑

单链表的设计与实现 代码如下:

//单链表设计与实现//2012-12-15//author:@quanwei#include<stdio.h>#include<stdlib.h>typedef struct node{int data;struct node *next;}NODE;/******************************************///函数名:Creat(int n);//参数:int n,传入线性表节点数//作用:建立节点数为 n+1 的带头结点的线性表//返回值:新链表的头指针/******************************************/NODE *Creat(int n){NODE *head,*pNew,*pWork;int num;head = (NODE*)malloc(sizeof(NODE));//建立头结点pWork = head;//工作指针初始化pWork->next = NULL;for(int i = 0;i < n;i++){pNew = (NODE*)malloc(sizeof(NODE));//建立新节点printf("请输入第%d项数据\n",i+1);//新节点赋值scanf("%d",&num);pNew->data = num;pWork->next = pNew;pWork = pNew;}pWork->next = NULL;//最后节点指向空return head;}/******************************************///函数名:Insert(NODE *head,int i,int data)//参数:NODE *head 线性表头指针,//int i 插入位置//int data插入元素//作用:在第i个节点后插入新节点//返回值:无/******************************************/void Insert(NODE *head,int i,int data){NODE *pWork = head ->next;NODE *pNew;int j = 1;while((j < i)&&(pWork != NULL)){//将pWork指向第i个节点pWork = pWork->next;j++;}if(pWork == NULL || j >i){//合法性判断printf("The location is illegal!");exit(0);}pNew = (NODE *)malloc(sizeof(NODE));pNew->data = data;//插入pNew->next = pWork->next;pWork->next = pNew;}/******************************************///函数名:Delete(NODE *head,int i)//参数:NODE *head 线性表头指针,//int i 需删除位置//作用:删除第i个节点//返回值:无/******************************************/void Delete(NODE *head,int i){NODE *pWork = head->next,*temp;int j = 1;while((j < i - 1)&&(pWork != NULL)){//将pWork指向第i个节点的前驱pWork = pWork->next;j++;}if(pWork == NULL || j > i -1){//合法性判断printf("The location is illegal!");exit(0);}temp = pWork->next;//temp指向第i个节点pWork->next = temp->next;//删除free(temp);}/******************************************///函数名:Display(NODE *head)//参数:NODE *head 线性表头指针,//作用:遍历整个线性表并打印全部元素//返回值:无/******************************************/void Display(NODE *head){NODE *pWork = head->next;while(pWork != NULL){printf("%4d",pWork->data);pWork = pWork->next;}}void main(){NODE *head ;int num;printf("Input the length of node:\n");scanf("%d",&num);head = Creat(num);printf("The current node is:");Display(head);Insert(head,3,4);Display(head);Delete(head,3);Display(head);}


原创粉丝点击