链表的一些操作

#include "stdafx.h"
#include<iostream>
#include<queue>
using namespace std;

typedef struct node{
        int data;
        struct node *next;
}Node,*List;

List createList(int N)//建立链表
{
	List head = (List)malloc(sizeof(Node));
	head->data = 0;
	head->next=NULL;
	int count = 0;
	List p = head;
	while(count<N)
	{	count++;
		List s = (List)malloc(sizeof(Node));
		s->data = count;
		s->next = NULL;
		p->next = s;
		p = s;
	}
	return head;
}

void traverse(List head)//遍历链表
{
	if(head == NULL)
	{
		return;
	}
	List p = head->next;
	while(p)
	{
		cout<<p->data<<" ";
		p = p->next;
	}
	cout<<endl;
}

bool sort(List head)//对链表进行排序
{
	if(head == NULL)
		return false;
	List pre,p,tailor,header;
	pre = head->next;
	if(pre==NULL)
		return false;
	header = pre;//记住第一个节点
	tailor = NULL;//tailor指向已排序序列的第一个节点
	while(tailor != header->next)//如果只剩下一个最后一个未排序节点,那么排序完成
	{
		pre = header;//初始化pre,和p指向前个节点
		p = pre->next;
		while(p!=tailor)//这个就相当于冒泡排序里面的j <n-i
		{
			if(pre->data > p->data)//把大的值往后面移动
			{
				int tmp = pre->data;
				pre->data = p->data;
				p->data = tmp;
			}
			pre = p;//移动指针
			p = p->next;
		}
		tailor = pre;//有序区新加入一个节点,所以tailor往前移动一个位置
	}
	return true;
}


void deleteNode(List head, int index)//删除第index个节点
{
	if(head == NULL)
		return;
	List pre, p;
	pre = p = head;
	int count = 0;
	
	while(p!=NULL && count<index)
	{
		pre = p;
		p = p->next;
		count++;
	}
	//cout<<count<<endl;
	if(p==NULL)
	{
		cout<<"illegal positioin!"<<endl;
		return;
	}
	pre->next = p->next;
	free(p);
}

bool insert(List head, int element,int index)//把data=element的节点插在链表的第index个位置上
{
	if(head == NULL || head->next==NULL)
		return false;
	List pre,p;
	pre = head;
	p = head;
	int count = 0;
	while(p != NULL&& count<index)
	{
		pre = p;
		p = p->next;
		count++;
	}
	if(count == index)
	{
		List no = (List)malloc(sizeof(Node));
		no->data = element;
		no->next = NULL;

		no->next = p;
		pre->next = no;
		return true;
	}
	else
	{
		cout<<"illegal position"<<endl;
	}
	return false;
}

int main()
{
	int N = 10;
	List head = createList(N);
	traverse(head);
	insert(head, 20, 2);
	insert(head, 15, 2);
	//deleteNode(head,20);
	traverse(head);
	sort(head);
	traverse(head);
    getchar();
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值