首页 >数据库 >mysql教程 >单链表的实现

单链表的实现

WBOY
WBOY原创
2016-06-07 14:51:111295浏览

#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>

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn