前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >单链表之插入结点

单链表之插入结点

作者头像
全栈程序员站长
发布2022-07-05 09:21:02
2300
发布2022-07-05 09:21:02
举报
文章被收录于专栏:全栈程序员必看

题:编写程序实现单链表的插入。【美国某著名计算机嵌入式公司2005年面试题】

答案:完整代买如下:

代码语言:javascript
复制
// P167_example1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <conio.h>

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

//建立单链表
node* create()
{
	node *head,*p,*s;
	int x, cycle = 1;
	head = (node *)malloc(sizeof(node));
	p = head;
	while(cycle)
	{
		std::cout<<"please input the data: ";
		std::cin>>x;
		std::cout<<std::endl;
		if(x != 0)
		{
			s = (node *)malloc(sizeof(node));
			s->data = x;
			p->next = s;
			p = s;
		}
		else
			cycle = 0;
	}
	head = head->next;
	p->next = NULL;
	return head;
}
//单链表测长
int length(node *head)
{
	int n = 0;
	node *p;
	p = head;
	while(p != NULL)
	{
		p = p->next;
		n++;
	}
	return n;
}
//单链表打印
void print(node *head)
{
	node *p;
	int n;
	n = length(head);
	std::cout<<"Now, These "<<n<<" records are: "<<std::endl;
	p = head;
	if(p != NULL)
	{
		while(p != NULL)
		{
			std::cout<<p->data<<" -> ";
			p = p->next;
		}
		std::cout<<std::endl;
	}
}
//单链表删除结点
node* del(node *head, int num)
{
	node *p1,*p2;
	p1 = head;
	while(num != p1->data && p1->next != NULL)
	{
		p2 = p1;
		p1 = p1->next;
	}
	if(num == p1->data)
	{
		if(p1 == head)
		{
			head = p1->next;
			free(p1);
		}
		else
		{
			p2->next = p1->next;
			free(p1);
		}
	}
	else
	{
		std::cout<<num<<" could not been found"<<std::endl;
	}
	return head;
}
//插入结点
node* insert(node *head, int num)
{
	node *p0,*p1,*p2;
	p1 = head;
	p0 = (node *)malloc(sizeof(node));	//待插入的结点
	p0->data= num;
	while(p0->data > p1->data && p1->next != NULL)
	{
		p2 = p1;
		p1 = p1->next;
	}
	if(p0->data < p1->data)
	{
		if(p1 == head)
		{
			p0->next = p1;
			head = p0;
		}
		else
		{
			p0->next = p1;
			p2->next = p0;
		}
	}
	else
	{
		p1->next = p0;
		p0->next = NULL;
	}
	return head;
}


int _tmain(int argc, _TCHAR* argv[])
{
	node *head;
	head = create();
	print(head);
	//删除结点
	int num;
	std::cin>>num;
	head = del(head, num);
	print(head);	//打印删除后的单链表
	//插入结点
	std::cin>>num;
	head = insert(head, num);
	print(head);
	return 0;
}

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/110061.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021年8月2,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档