欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  数据库

单链表的实现

程序员文章站 2023-12-26 23:30:03
...

#include iostreamusing namespace std;struct listNode{int data; //存放本节点的数据 struct listNode* next; //存放下一个节点的位置 }; void insertNode(listNode *head, int pos, int value) {int step = 0;listNode* temp = new listNode;listNode* no

#include 
using namespace std;

struct listNode{
	int data;              //存放本节点的数据 
	struct listNode* next; //存放下一个节点的位置 
};
 
 
 
void insertNode(listNode *head, int pos, int value) {
	int step = 0;
	listNode* temp = new listNode;
	listNode* node = head;  //在后面改变了head的指向,需要先保存初始的head的指向 
	temp->data = value; 	//保存链表头的原始位置 
	while (step next;
		step++;
	} 
	temp->next = head->next;
	head->next = temp;
	head = node;	
}

void deleteNode(listNode *head, int pos) {
	listNode* node = head; //在后面改变了head的指向,需要先保存初始的head的指向 
	int step = 0;				
	while (step next;
		step++;
	}
	listNode *previous = head->next; 
	head->next = head->next->next;	
	delete previous; 	//delete一个指针其实是delete掉它指向的对象,delete掉head->next指向的对象 
	head = node;		
}

bool isEmpty(listNode *head) {
	return head->next == NULL? true : false; 
}

int size(listNode *head) {
	listNode* node = head;
	int count = 0;
	while (head->next != NULL) {
		count++;
		head = head->next;
	}
	head = node;
	return count;
}

//遍历整个链表 
void traverse(listNode* head) {
	listNode *node = head;
	head = head->next;
	while (head != NULL) {
		cout data next;
	}
	head = node;
}

void clear(listNode* head) {
	listNode* temp;
	listNode* node = head;
	//这里要理解一下 
	while(head->next != NULL) {
		temp = head->next->next;
		delete head->next;
		head->next = temp;
	}
	head = node;
}

上一篇:

下一篇: