单链表的实现

#include <iostream>
#include < windows.h>
using namespace std;


typedef struct Node{
	int data;
	Node* next;
}Student;


Student* createLink(int n) {

	Student* head = new Student; //先创建一个头指针
	Student* pre = head; //保存头指针的地址
	for (int i = 0; i < n; i++)
	{
		Student* p = new Student;  //需要添加的数据
		printf("请输入要添加的数据: ");
		cin >> p->data;
		pre->next = p;  //一个指针的netx指向新创建的节点
		pre = p;  //然后让临时节点的地址为新创建的节点的地址
		p->next = NULL;  ///将节点的nex为空
	}

	return head;
}

int lengh(Student* head)
{
	Student* p = head->next;
	int count = 0;
	while (p != NULL) {
		count++;
		p = p->next;
	}
	return count;
}


void removeElement(Student* head, int n) {
	
	if (n > lengh(head) || n < 0)
	{
		throw "out range";
	}
	Student* pre = head; //临时存储

	for (int i = 0; i < n; i++)  //获取要存储的上一个地址
	{
		pre = pre->next;
	}
	Student* p = pre->next; //要删除的节点
	pre->next = p->next; //将上一个节点指向要删除的节点的下一个节点
	delete p;




}


void IinsertLink(Student* head,int n) {
	
	if (n>lengh(head)|| n<0)
	{
		throw "out range";
	}

	Student* newNode = new Student; //申请新的节点存储数据
	Student* pre = head; //临时存储
	for (int i = 0; i < n; i++)  //获取要存储的上一个地址
	{
		pre = pre->next; 
	}
	newNode->data = n; //赋值
	newNode->next = pre->next; //新节点的next指向原先的下一个节点
	pre->next = newNode; //再将要插入节点上一个节点的指向新增的节点

}






void display(Student* head)
{
	Student* p = head->next;

	while (p != NULL)
	{
		cout << p->data << endl;
		p=p->next;
	}

}






void main()
{
	Student* head = createLink(5);
	removeElement(head, 2); //在2的位置插入2
	display(head);
	
	
}
   




发表评论 / Comment

用心评论~