C++单链表

完善上一篇的单链表

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
using namespace std;
struct node
{
	int data;
	struct node* next;
};
struct node* head;
struct node* Createlink(struct node* head,int n) {
	head = (struct node*)malloc(sizeof(struct node));
	head->next = NULL;
	struct node* tail = head;
	while (n-->0)
	{
		struct node* p= (struct node*)malloc(sizeof(struct node));
		cin >> p->data;
		p->next = NULL;
		tail->next = p;
		tail = p;
	}
	return head;
}
void Print(struct node* head) {
	struct node* p = head;
	p = p->next;
	while (p!=NULL)
	{
		cout << p->data << " ";
		p = p->next;
	}
	cout << endl;
}
void h_insert(struct node* head) {
	struct node* p = (struct node*)malloc(sizeof(struct node));
	cin >> p->data;
	struct node* temp = head->next;
	head->next = p;
	p->next = temp;
}
void t_insert(struct node* head) {
	struct node* p = head;
	while (p->next!=NULL)
	{
		p = p->next;
	}
	struct node* temp = (struct node*)malloc(sizeof(struct node));
	cin >> temp->data;
	temp->next = NULL;
	p->next = temp;
}
void h_delete(struct node* head) {
	struct node* temp = head->next;
	head->next = temp->next;
	free(temp);
}
void t_delete(struct node* head) {
	struct node* p = head;
	struct node* temp = head;
	while (p->next != NULL)
	{
		temp = p;
		p = p->next;
	}
	temp->next = NULL;
	free(p);
}
void index_delete(struct node* head,int x) {
	struct node *p, *q;
	p = head;
	while (p->next!=NULL)
	{
		q = p->next;
		if (q->data == x) {
			p->next = q->next;
			free(q);
			q->next = NULL;
			continue;
		}
		p = p->next;
	}
}
void index_insert(struct node* head,int index)
{
	int i = 0;
	struct node* p = head;
	while (p != NULL && i < index)
	{
		p = p->next;
		i++;
	}
	if (p==NULL||i>index)
	{
		cout<<"数组越界"<<endl;
		return;
	}
	struct node* q = (struct node*)malloc(sizeof(struct node));
	cin >> q->data;
	struct node* temp = p->next;
	p->next = q;
	q->next = temp;
}
int main() {
	int n;
	cin >> n;
	head=Createlink(head, n);
	index_insert(head,2);
	Print(head);
	system("pause");
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值