Home >Database >Mysql Tutorial >单链表的实现

单链表的实现

WBOY
WBOYOriginal
2016-06-07 14:51:111291browse

#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 <iostream>
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;
}
</iostream>

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn