线性表学习笔记-单链表实现(2)

把线性表的各种应用写了一下。比上次根伟完整了下。释放存储空间没有写。只是写了下思路。
#include<iostream>  
# include "stdio.h"  
# include "stdlib.h"  
# include "malloc.h"  
  
using namespace std;  
typedef int elemtype;  
typedef struct linknode {  
    elemtype data;  
    struct linknode *next;  
} nodetype,*linklist;  
  
nodetype* create();  //建立链表
void output(nodetype* h); //输出链表
int  len(nodetype *h);//求链表长度
nodetype* find(nodetype* h,int i);//返回第i个位置的指针
nodetype* insert(nodetype* h,int i,int x);//在第i个位置插入x
nodetype* dele(nodetype*h,int i); //删除第i个数
void  main()  
{  
	int lenth;
	nodetype*q;
    nodetype* head;  
	head=create();  
    output(head);  
	lenth=len(head);
	cout << lenth << endl;
	cout << "查找第3个数的值。" << endl;
	q=find(head,3);
	cout << q->data << endl;
	cout << "在第3个位置插入100" << endl;
	insert(head,3,100);
	output(head);
	cout << "删除第4个数。" << endl;
	dele(head,4);
	output(head);

	
}  
  
 nodetype* create()  
{  
    nodetype *r,*s,*la;  
    int x;  
    cout <<"输入0表示结束。" << endl;  
    cout << "输入结点值:" << endl;  
    cin >> x;  
    la=(linklist)malloc(sizeof(linknode));  
    la->next=NULL;  
    r=s=la;  
    while(x!=0)  
    {     
        s=(linklist)malloc(sizeof(linknode));  
        s->data=x;  
        r->next=s;  
        r=s;  
        cout <<"输入结点值:" << endl;  
        cin >> x;  
    }  
    r->next=NULL;   
	return la;
}  
  
void output(nodetype* h)  
{  
    nodetype* q;  
    q=h->next;  
    while(q!=NULL)  
    {  
        cout << q->data <<  " ";  
        q=q->next;  

    }  
    cout << "end" << endl;  
  
}  

int  len(nodetype *h)
{
	int i=0;
	nodetype* p;
	p=h;
	while(p->next!=NULL) // 这个地方出错了,原来写的是p->next->data!=0.错误的,是指针为null,而非data。
	{
		p=p->next;
		i++;
	}
	return i;
}

/* nodetype* find(nodetype* h,int i)// 此函数查找的是所找数的下一个
{
	int j;
	nodetype* p;
	p=h;
	for(j=0;j<=i;j++) //这个地方出错,应该是 j<i.
		p=p->next;
	return p;
}*/

 nodetype* find(nodetype* h,int i)
{
	int j;
	nodetype* p;
	p=h;
	for(j=0;j<i;j++)
		p=p->next;
	return p;
}
nodetype* insert(nodetype* h,int i,elemtype x)//在单链表中第i个位置,插入x
{
	nodetype* p,* s;
	p=find(h,i-1);
	s=(nodetype*)malloc(sizeof(nodetype)); //s=(*nodetype)malloc(sizeof(nodetype));错误
	s->data=x;
	s->next=p->next;                         // s=p->next;首次犯错
	p->next=s;
	return h;
}

nodetype* dele(nodetype*h,int i)
{
	nodetype* p,* q;
	p=find(h,i-1);
	q=p->next;
	p->next=q->next;
	free(q);
	return h;
}

/*void dispose(nodetype* h)//释放存储空间
{
	nodetype* p,* q;
	if(h->next==NULL)
		free(h);
	else
		p=h;
		q=p->next;
	while(q!=0)
	{ 
		free(p);
		p=q;
		q=q->next;	
	}
	free(p);
}*/


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值