链表的创建等一系列操作

#include <stdio.h >
#include <iostream>

using namespace std;

typedef int DataType; 
typedef struct Node
{
	DataType data;
	struct Node * next;
}Node,*LinkList;

void CreateListH(LinkList &L)//头插法 
{
	cout<<"请输入数\n";
	Node *s;
	int c;
	L = new Node;
	L->next = NULL;
    cin>>c;
    while (c != 0)
    {
    	s = new Node;
    	s->data = c;
    	s-> next = L->next;
    	L->next = s;
        cin>>c;
    	
	}
}
void CreateListT(LinkList &L)//尾插法 
{
	int c;
	cout<<"please input\n";
	Node *r,*s;
	L = new Node;
	L->next = NULL;
	r = L;
	cin >> c;
	while(c != 0)
	{
		s = new Node;
		s->data = c;
		r->next = s;
		r = s;
		cin >> c;
	}
	r->next = NULL;
}



void Output(LinkList L)// l 头结点 
{
	Node *p;
	for(p=L->next;p != NULL;p=p->next)
	printf("%d  ",p->data);
	printf("\n");
}

Node * GetData(LinkList L,int i) //第i个节点的位置 
{
	int j;
	Node *p;
	cout << "input第几个节点\n";
	cin >> i;
	i = i-1;
	if (i < 0)
	  	return NULL;
	p = L;//p  point to head
	j = 0;//count++
	while (p->next != NULL && j < i)
	{
		p = p->next;
		j++;
	}
	if (i == j) 
		return p;
	else 
		return NULL;
}


int Length(LinkList L)//计算长度 
{
	Node *p;
	int len = 0;
	p  = L->next;
	while(p != NULL)
	{
		p= p->next;
		len++;
	}
	 return len;
}



void Delete(LinkList &L,int i)//删除 
{
	Node *pre,*r;
	cout << "please input which node will be deleted\n";
	pre = GetData(L,i-1);
	if (pre == NULL ||  pre->next == NULL)
		printf("delete is unreasonable\n");
	else 
		{
			r = pre->next;
			pre->next = r->next;
			delete(r);
		}
}


void Insert(LinkList &L,int i,DataType x)//在第i个节点前插入x的新节点
{
	Node *pre,*s;
	cout << "input x (待插入)\n";
	cin >> x;
	pre = GetData(L,i-1);
	if (pre == NULL)
		printf("error\n");
	else 
		{
			s = new Node;
			s->data = x;
			s->next = pre->next;
			pre->next = s;
			}	
	
	
 } 


int main()
{
	Node *L;
	int c,d,x,i;
	cout<<"choose  way\n";// 头插还是尾插 
	cin >> c;
	if (c == 1)
	    CreateListH(L);
	
	else
		CreateListT(L);
	d = Length(L);
	cout << d << endl;
	Insert(L, i,x);
	Output(L);
	Delete(L, i);
	Output(L);
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值