1. 程式人生 > >連結串列的建立、插入、刪除、逆序、遍歷

連結串列的建立、插入、刪除、逆序、遍歷

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;

typedef struct node{
	int data;
	struct node * next;
}node;

int main(){
	void create(node * & list);
	void count(node * list);
	void add(node * list);
	void print(node * list);
	void delet(node * & list,int target);
	void reverse(node * & list);

	node * list;

	create(list);
	count(list);

	add(list);
	count(list);
	print(list);

	cout<<"Input the element you want to delete:";
	int target;
	cin>>target;
	delet(list,target);
	print(list);

	cout<<"After reverse:"<<endl;
	reverse(list);
	print(list);
}

void create(node * & list){
	int newData;
	node * p;
	bool first=true;

	cout<<"Input newData(-1 to stop):";
	while(cin>>newData && newData!=-1){
		node * newNode=(node*)malloc(sizeof(node));
		newNode->data=newData;
		newNode->next=NULL;

		if(first){
			list=newNode;
			first=false;
			p=list;
		}
		else
		{
			p->next=newNode;
			p=p->next;
		}
	}
}

void count(node * list){
	int length=0;

	while(list!=NULL){
		length++;
		list=list->next;
	}
	cout<<"The length of list is "<<length<<"."<<endl;
}

//插入
void add(node * list){
	if(list==NULL){
		cout<<"list has not been created!"<<endl;
		return;
	}

	while(list->next!=NULL)
		list=list->next;

	int newData;
	node * newNode;
	cout<<"Add data of new nodes(-1 to stop):";
	while(cin>>newData && newData!=-1){
		newNode=(node *)malloc(sizeof(node));
		newNode->data=newData;
		newNode->next=NULL;

		list->next=newNode;
		list=newNode;
	}
}

void print(node * list){
	while(list!=NULL){
		cout<<list->data<<" ";
		list=list->next;
	}
	cout<<endl;
}

//刪除
void delet(node * & list,int target){

	if(list->data==target){
		node * t=list;
		list=list->next;
		free(t);

		delet(list,target);
	}

	node * pw=list;
	node * w;
	while(pw->next!=NULL){
		if(pw->next->data==target){
			w=pw->next;
			pw->next=w->next;
			free(w);
		}
		else
			pw=pw->next;
	}
}

//倒序
void reverse(node * & list){
	node * pw=list;
	node * w=pw->next;

	while(w!=NULL){
		pw->next=w->next;
		w->next=list;

		list=w;

		w=pw->next;
	}
}