头插法
//头插法
#include <iostream>
using namespace std;
#include <string>
struct ListNode {
int data;
ListNode* next;
};
ListNode * CreateListNode(ListNode *L) {
int a;
cin>>a;
while(a!=0) {
ListNode *p = new ListNode;
p->data = a;
p->next = L->next;
L->next = p;
cin>>a;
}
cout<<"end"<<endl;
}
void display(ListNode *L) {
while(L->next) {
cout << L->next->data<<" ";
L = L->next;
}
}
int main(int argc, const char * argv[]) {
//设置头节点
ListNode *L = new ListNode;
//将头节点的指针域置空
L->next = NULL;
CreateListNode(L);
display(L);
}
尾插法
#include <iostream>
using namespace std;
struct List{
int data;
List *next;
};
List *createList(List * head)
{
int x;
cin>>x;
while(x!=0)
{
List *s = new List;
s->data = x;
head->next = s;
head = s;
s->next = NULL;
cin>>x;
}
}
void display(List *head)
{
while(head->next)
{
cout<<head->next->data<<"\t";
head = head->next;
}
cout<<endl;
}
int main()
{
List *head = new List;
head->next = NULL;
createList(head);
display(head);
return 0;
}