#include<iostream>
#include<windows.h>
using namespace std;
struct Node {
int data ;
Node *link ;
};
class LinkList {
public:
LinkList () {} ;
bool IsEmpty ( ) {return (first->link != NULL) ?false : true ;}
void create(Node *first ,int n){ //n就是第一个结点的
for(int i=0 ; i< n ; i++){
cout<<"请输入您所想给的元素的data值"<<endl;
int n_data ;
cin >> n_data ;
Node *cur = new Node ;
cur->link =first ->link ;
first->link = cur ;
cur->data = n_data ;
first = cur ;
}
}
void print(Node *first){
Node *cur = first->link ;
while (cur != NULL)
{cout<<cur->data<<endl;
cur = cur->link ;}
}
Node *Locate (Node *first ,int w_place ) { // 定位函数,插入与删除时用来确定某一位置
int k = 0 ;
Node *cur = first ;
while( k != w_place ) {
cur = cur->link ;
k++;
}
return cur ;
}
void Insert (Node *first){
cout<<"请输入您想插入的位置 :" ;
int place ;
cin >> place ;
Node *cur = Locate(first,place) ;
Node *newNode = new Node ;
cout<<"请输入您想插入的元素的值 :";
int data ;
cin >> data ;
newNode->data = data ;
newNode->link = cur->link ;
cur->link = newNode ;
}
void Delete(Node *first){
cout<<"请输入您想删除的位置 : " ;
int place ;
cin >> place ;
Node *cur =Locate (first,place -1 ) ;
cur->link =cur->link->link ;
}
protected:
Node *first ;
} ;//单链表怎么建议,首先要先建立一个头结点,然后不断的插入,这样就就形成一个单链表
void main() {
LinkList test ;
int answer ;
cout<<"请输入您想创建的链表长度 :";
cin >> answer ;
Node *head = new Node ;
head->data = 10 ;
head->link = NULL ;
test.create(head,answer) ;
test.print(head) ;
test.Insert(head) ;
test.print(head) ;
test.Delete(head);
test.print(head) ;
system("pause") ;
}
数据结构手写单链表(较简单)
最新推荐文章于 2023-10-21 10:04:41 发布