单链表操作

程序有问题,需改进。

#include <iostream>
using namespace std;

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

//create a list.
node *create()
{
	node *head, *first, *second;
	head = new(node);
	first = head;
	int num;
	
	cout << "Now input the list:\n";
	while(cin >> num && num)
	{
		cout << "number:" << num << endl;
		second = new(node);
		second->data = num;
		first->next = second;
		second->next = NULL;
		first = second;
	}
	if(first - head == 0)
		return NULL;
	head = head->next;
	return head;
}

//打印链表.
void printList(node *head)
{
	cout << "Now output the list:\n";
	
	//list is null.
	if(head == NULL)
		return ;
	//list is not null.
	else
	{
		node *p = head;
		while(p != NULL)
		{
			cout << p->data << " ";
			p = p->next;
		}
		cout << endl;
	}
}

//删除节点.
node *deleteNode(node *head, int num)
{
	node *first, *second;
	first = head;	
	
	while(num != first->data && first->next != NULL)
	{
		second = first;
		first = first->next;
	}
	
	//---找到了要删除的节点.
	if(num == first->data)
	{
		//头结点.
		if(first == head)
			head = head->next;
		//不是头结点.
		else
			second->next = first->next;
		free(first);
	}
	
	//---没有找到要删除的节点.
	else
		cout << "can not find the node!\n";
	return head;
}

//插入节点.
node *insertNode(node *head,int num)
{
	node *newNode = new(node);
	newNode->data = num;
	node *first = head, *second;
	
	while(num > first->data && first->next != NULL)
	{
		second = first;
		first = first->next;
	}
	
	//---未达到链表结尾,即在链表头部或内部插入节点.
	if(num <= first->data)
	{
		//插入头结点之前.
		if(first == head)
		{
			newNode->next = head;
			head = newNode;
		}
		//插入头结点之后.
		else
		{
			newNode->next = first;
			second->next = newNode;
		}
	}
	//---达到链表结尾,即在链表尾部插入.
	else
	{
		first->next = newNode;
		newNode->next = NULL;//注意将为节点的指针置为空.
	}
	
	return head;
}

//求链表长度.
int len(node *head)
{
	int cnt = 0;
	node *index = head;
	while(index != NULL)
	{
		cnt++;
		index = index->next;
	}
	return cnt;
}

//单链表排序.
node *sort(node *head)
{
	if(head == NULL || head->next == NULL)
		return NULL;
	node *first = head;
	node *second = head->next;
	int n = len(head);cout << "the lenth is: " << len(head) << endl << endl;
	int temp;
	for(int i = 1;i < n;i++)
	{
		//第i趟比较.
		for(int j = 1;j < n-i;j++ )
		{
			if(first->data > second->data)
			{
				temp = first->data;
				first->data = second->data;
				second->data = temp;
			}
			first = first->next;
			second = second->next;
		}
	}
	return head;
}


int main()
{
	node *p = create();cout << endl << "*p:" << *p->data << endl;
	printList(p);
	p = deleteNode(p,5);
	printList(p);

	p = sort(p);
	printList(p);

	p = insertNode(p,8);
	printList(p);

	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值