#include "bits/stdc++.h"
using namespace std;
#define ERROR -1
#define OK 0
typedef struct LNode {
int elem;
struct LNode *next;
} LNode, *LinkList;
int TheTailInterpolation(LinkList &L, int n) {
LinkList s, r;
L = new LNode;
if (L == NULL) {
cerr << "结点创建失败" << endl;
return ERROR;
}
L->next = NULL;
r = L;
while (n--) {
s = new LNode;
if (s == NULL) {
cerr << "结点创建失败" << endl;
return ERROR;
}
cout << "请输入您要插入的元素:" << endl;
cin >> s->elem;
s->next = NULL;
r->next = s;
r = s;
}
return OK;
}
LinkList FindMiddle(LinkList L) {
LinkList p, q;
p = L;
q = L;
while ((p != NULL) && (p->next != NULL)) {
p = p->next->next;
q = q->next;
}
return q;
}
int ListPrint_L(LinkList L) {
LinkList p;
p = L->next;
while (p != NULL) {
cout << p->elem << "\t";
p = p->next;
}
cout << endl;
}
int main() {
LinkList L, mid;
int i;
cout << "创建单链表L:" << endl;
cout << "请输入单链表的表长:" << endl;
cin >> i;
TheTailInterpolation(L, i);
cout << "单链表的数据为:" << endl;
ListPrint_L(L);
mid = FindMiddle(L);
cout << "单链表中间结点数据为:" << mid->elem << endl;
return 0;
}
|