链表 实现复杂的数据结构
`#include
using namespace std;
struct Node{
int data;
Node* next;
};
Node* CreateNode(int data){
Node* newNode=new Node();
newNode->data=data;
newNode->next=NULL;
return newNode;
}
void traverseLinkedList(Node* head){
Node* current=head;
while(current!=NULL){
cout<
current=current->next;//TODO
}
cout<<endl;
}
void insertAtPosition(Node* head,int data,int a){
Node* current = head;
int count = 1;
while(current!=NULL&&count<a){
current=current->next;
count++;//TODO
}
if(current==NULL){
cout<<"链表的长度不足,无法在第三个位置上再插入一个新节点"<<endl;
return;//TODO
}
traverseLinkedList(head+1);
Node* newNode=CreateNode(data);
newNode->next=current->next;
current->next=newNode;
}
void deleteNodeAtPosition(Node* head,int a){
Node* current = head;
Node* previous = head;
int count = 1;
if(a1){
cout<<"不能删除头节点";//TODO
}
while(current!=NULL&&count<a){
previous=current;
current=current->next;
count++;//TODO
}
if(currentNULL){
cout<<"链表长度不足";
return;//TODO
}
Node* toDeleteNode=head->next;
head->next=toDeleteNode->next;
delete toDeleteNode;
}
int main(){
int a;
Node* head=CreateNode(1);
cin>>a;
Node*current=head;
for(int i=2;i<=5;++i){
current->next=CreateNode(i);
current=current->next;//TODO
}
traverseLinkedList(head);
// cout<<"插入一个新节点后的链表是:";
// insertAtPosition(head,100,a);
// traverseLinkedList(head);
cout<<"删除一个新节点后的链表是:";
deleteNodeAtPosition(head,a);
traverseLinkedList(head);
return 0;
}
`
浙公网安备 33010602011771号