C++实现单向链表
2012-09-07 17:32
645 查看
#include <iostream>
using namespace std;
int counter;
struct Node{
Node* next;
int data;
bool hasNext;
};
void addNode(Node* head,Node* node){
node->next=head->next;
head->next=node;
counter+=1;
}
void showListData(Node* head){
head=head->next;//ignore the head node
while(true){
cout<<head->data<<"\t";
head=head->next;
if(head->next==NULL){
cout<<head->data<<endl;
break;
}
}
cout<<endl;
}
void showListForLoop(Node* head){
for(int i=0;i<=counter;i++){
cout<<head->data<<"\t";
head=head->next;
}
}
void deleteNode(Node* head,int index){
if(index==1){
head->next;
}
Node* p = head;
for(int i = 1;i<index;i++){
p=p->next;
}
Node* node = p->next;
p->next = p->next->next;
delete(node);
}
void main(){
Node* head = new Node;
head->next=NULL;
head->data=100;
for(int i=1;i<=10;i++){
Node* node = new Node;
node->data=i;
addNode(head,node);
}
cout<<"counter:"<<counter<<endl;
showListData(head);
deleteNode(head,5);
showListData(head);
// showListForLoop(head);
}
using namespace std;
int counter;
struct Node{
Node* next;
int data;
bool hasNext;
};
void addNode(Node* head,Node* node){
node->next=head->next;
head->next=node;
counter+=1;
}
void showListData(Node* head){
head=head->next;//ignore the head node
while(true){
cout<<head->data<<"\t";
head=head->next;
if(head->next==NULL){
cout<<head->data<<endl;
break;
}
}
cout<<endl;
}
void showListForLoop(Node* head){
for(int i=0;i<=counter;i++){
cout<<head->data<<"\t";
head=head->next;
}
}
void deleteNode(Node* head,int index){
if(index==1){
head->next;
}
Node* p = head;
for(int i = 1;i<index;i++){
p=p->next;
}
Node* node = p->next;
p->next = p->next->next;
delete(node);
}
void main(){
Node* head = new Node;
head->next=NULL;
head->data=100;
for(int i=1;i<=10;i++){
Node* node = new Node;
node->data=i;
addNode(head,node);
}
cout<<"counter:"<<counter<<endl;
showListData(head);
deleteNode(head,5);
showListData(head);
// showListForLoop(head);
}
相关文章推荐
- [04.28更新]C++ 单向链表的实现
- C++模板实现的单向链表
- 用c++实现简单的单向链表
- 单向链表 (Singly linked list) 的C++实现
- 数据结构之单向链表的实现【C++】
- C++:单向链表实现
- 单向链表(c++实现)
- 《数据结构之链表篇》--单向链表的C++实现
- C++实现单向循环链表
- 单向链表的C++实现
- c++实现单向链表反转的学习总结
- 单向链表的c++实现
- C++ 实现单向链表
- C++实现单向链表(2)
- c++实现单向单链表及常见面试题
- 使用C++实现单向链表
- 单向循环链表的C++实现
- 单向链表之C++实现
- 利用 C++ 单向链表实现队列
- C++异常机制的实现方式和开销分析 (大图,编译器会为每个函数增加EHDL结构,组成一个单向链表,非常著名的“内存访问违例”出错对话框就是该机制的一种体现)