C++实现单向链表

来源:互联网 发布:股票app制作软件 编辑:程序博客网 时间:2024/06/05 21:19
#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);
}
原创粉丝点击