当前位置:Gxlcms > mysql > 单链表的实现

单链表的实现

时间:2021-07-01 10:21:17 帮助过:27人阅读

#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 < pos) {	//感觉这里需要记忆,比较难理解 
 		head = head->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 < pos) {
		head = head->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 << head->data << endl;
		head = head->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;
}

人气教程排行