单链表建立,插入,删除,查找,遍历操作

单链表建立,插入,删除,查找,遍历操作

// Link.cpp : 定义控制台应用程序的入口点。
//单链表
#include "stdafx.h"
#include 
#include 
using namespace std;

typedef struct node {
	int data;//节点内容
	node *next;//下一个节点
}node;

//创建单链表
node *create(){
	node *head,*p,*q;
	int i=0; //单链表中数据的个数
	int a=-1;
	head=new node;//创建头节点
	head->next=NULL;
	while (1)
	{
		cout<<"please input the data(input -1,quit):";
		cin>>a;
		if (-1==a) //如果输入的是-1,退出
		{
			break;
		}
		p=new node;
		p->data=a;
		p->next=NULL;//链表的最后一个指针为NULL
		if (++i==1) //链表只有一个元素
		{           //连接到head的后面
			head->next=p;
		}
		else{
			q->next=p;//连接到链表尾端
		}
		q=p;//q指向末节点
	}
	return head;
}

//单链表的测长
int length(node *head){
	int len=0;
	node *p=head->next;
	while (p!=NULL){//遍历链表
		++len;
		p=p->next;
	}
	return len;
}

//打印单链表
void print(node *head){
	node *p=head->next;
	int index=0;
	if (p==NULL)//链表为NULL
	{
		cout<<"Link is empty!"<data<next;
	}
}

//查找单链表pos位置的节点,返回节点指针
//pos 从o开始,0 返回head节点
node *search_node(node *head,int pos){
node *p=head->next;
if (pos<0)//pos 位置不正确
{
	cout<<"incorrect position to search node"<next)==NULL)
	{
		cout<<"incorrect position to search node"<data=data;
	p->next=NULL;
	node *q=head;
	if (pos==0)
	{
		p->next=q->next;
		q->next=p;
	}
	while (pos)
	{
		q=q->next;
		--pos;
	}
	if (q!=NULL)
	{
	p->next=q->next;//p指向原pos节点的后一个节点
	q->next=p; //p插入到pos的后面
	}
	return head;
}
//删除单链表的pos位置的节点,返回链表头指针
//pos从1开始计算,1表示删除head后的第一个节点
node *delete_node(node *head,int pos){
		node *q=head->next;
		node *p=NULL;
	if (q==NULL)
	{
		cout<<"Link is empty!"<next;//得到位置pos的节点
	}
	if (q!=NULL && q->next!=NULL)
	{
		p=q->next;
		q->next=p->next;
		delete p;
	}
	return head;
}
int _tmain(int argc, _TCHAR* argv[])
{
	node *head=create();//创建单链表
	cout<<"Length:"<data<

单链表的排序

//设有一个没有表头结点的单链表,其结点的值均为整数,且按绝对值从小到大的顺序链接。
//试设计一种算法,将此链表中的值从小到大排列.
//算法设计:冒泡排序,借用数组中的冒泡排序来对链表进行排序
//程序示例:(C语言实现)
#include 
#include 

//申明链表
typedef struct node
{
int num;
struct node *next;
}list;

void Bubble_sort(list *&L);//链表的冒泡排序
void Dis_list(list *&L);//遍历单链表

int main()
{
//建表
list *r,*s,*p;
int n;//存储数据的个数
printf("请输入你要存储数据的个数:\n");
scanf("%d",&n);
    s=(list *)malloc(sizeof(list));
scanf("%d",&s->num);
s->next=NULL;
p=s;
for(int i=1;i<=n-1;i++)
{
   r=(list *)malloc(sizeof(list));
   scanf("%d",&r->num);
        p->next=r;
   p=r;
}
p->next=NULL;
printf("排序前:\t");
Dis_list(s);
   //排序
   Bubble_sort(s);
   printf("排序后:\t");
   Dis_list(s);
   return 0;
}

void Dis_list(list *&L)
{
list *r;
r=L;
while(r!=NULL)
{
   printf("%d\t",r->num);
   r=r->next;
}
printf("\n");
}

void Bubble_sort(list *&L)
{
list *r,*s;
int temp;
for(r=L;r->next!=NULL;r=r->next)
{
   for(s=L;s->next->next!=NULL;s=s->next)
   {
    if(s->num>s->next->num)
    {
     temp=s->num;
     s->num=s->next->num;
     s->next->num=temp;
    }
   }
}
}



你可能感兴趣的:(数据结构)