首先,对于单链表来说,带头结点比不带头结点的好处是很大的,体现在对其的基本操作中,
这里,特别说明下,头结点可以看做是一个标志,并没有具体的数值;
#includeusing namespace std; typedef struct LNode { int data; struct LNode* next; }LNode,*Linklist; //LNode*强调这是一个结点,Linklist强调这是一个链表,两者本质上是一样的 //初始化 void Initlist(Linklist& L) { L = (LNode*)malloc(sizeof(LNode)); if (L == NULL) cout << "内存不足,分配失败!" << endl; L->next = NULL; cout << "初始化成功!" << endl; } void EmptyIf(Linklist L) { if (L->next == NULL) cout << "链表为空!" << endl; else cout << "链表不为空!" << endl; } void Insertlist(Linklist L, int location, int e) { if (location < 1) cout << "插入位置越界!" << endl; LNode* p; int i = 0; //i为第i个位置,这里将头结点看作第0个位置 p = L; while (p != NULL && i < location - 1) //循环作用,p指针指向第(location-1)的位置 { p = p->next; i++; } if (p == NULL) cout << "插入位置不合法!" << endl; LNode* s = (LNode*)malloc(sizeof(LNode)); //创建新结点,即为要插入的结点 s->data = e; s->next = p->next; p->next = s; cout << "插入成功!" << endl; } Linklist HeadInsertlist(Linklist L) //头插法 { int x = 0; cin >> x; while (x != 999) { LNode* s = (LNode*)malloc(sizeof(LNode)); s->data = x; s->next = L->next; L->next = s; cin >> x; } return L; } Linklist NextInsertlist(Linklist& L) //尾插法 { int x = 0; LNode* r = L;//尾结点 cin >> x; while (x != 999) { LNode* s = (LNode*)malloc(sizeof(LNode)); s->data = x; s->next = r->next; r->next = s; r = s; cin >> x; } r->next = NULL; return L; } void Printlist(Linklist L) { LNode* p; p = L; if (p->next == NULL) cout << "链表为空!" << endl; else { p = p->next; while (p != NULL) { cout << p->data << " "; p = p->next; } } } int main() { Linklist L; Initlist(L); //HeadInsertlist(L); NextInsertlist(L); //EmptyIf(L); //Insertlist(L, 1, 1); //Insertlist(L, 2, 2); //Insertlist(L, 3, 3); Printlist(L); return 0; }



