一、创建链表,顺序增加数据,遍历链表操作
/** *C语言实现,用了三个指针操作,没用构造函数 */#includeusing namespace std;struct student { int data; struct student* next;};int main(){ int data; struct student *head,*tail,*temp; head = NULL; while(cin>>data && data!=-1) { temp = (struct student*)malloc(sizeof(struct student)); temp->data = data; temp->next = NULL; if(head==NULL) { head = temp; tail = head; } else { tail->next = temp; tail = temp; } } tail = head; while(tail!=NULL) { cout< data< next; } system("pause"); return 0;}
/** *C/C++实现,用了三个指针操作,用了构造函数 */#includeusing namespace std;struct student { int data; struct student* next; student(int a) { this->data = a; this->next = NULL; }};int main(){ int data; struct student *head,*tail,*temp; head = NULL; while(cin>>data && data!=-1) { if(head==NULL) { head = new student(data); tail = head; } else { temp = new student(data); //temp用来接收新节点,这样tail的next不会丢失 tail->next = temp; tail = temp; } } tail = head; while(tail!=NULL) { cout< data< next; } system("pause"); return 0;}
/** *C/C++实现,用了两个指针操作,用了构造函数 */#includeusing namespace std;struct student { int data; struct student* next; student(int a) { this->data = a; this->next = NULL; } student(int a, struct student* p) { p->next = this; this->data = a; this->next = NULL; }};int main(){ int data; struct student *head,*tail; head = NULL; while(cin>>data && data!=-1) { if(head==NULL) { head = new student(data); tail = head; } else { tail = new student(data, tail); } } tail = head; while(tail != NULL) { cout< data< next; } system("pause"); return 0;}
二、(待续)