您的位置:首页 > 编程语言 > C语言/C++

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);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ include null