编程注意事项:
1.尾插法注意输入数据结束之后尾指针标记为空
2.复习:头插法的重要应用是链表逆置
3.if (cin.get() == '\n')break; 应该放置在循环的最后,因为输入数据之后是紧接着回车,如果放置在cin的后面,那么最后输入的数据就读不进去了。
typedef struct LNode {
int data;
struct LNode *next;
}LNode,*LinkList;
LinkList createHead() {
LinkList L = (LNode*)malloc(sizeof(LNode));
L->next = NULL;
int x;
while (true)
{
cin >> x;
LNode* p = (LNode*)malloc(sizeof(LNode));
p->data = x;
p->next = L->next;
L->next = p;
if (cin.get() == '\n')break;
}
return L;
}
void print(LinkList L) {
LNode *p = L->next;
while (p)
{
cout << p->data<<endl;
p = p->next;
}
}
LinkList createTail() {
LinkList L = (LNode *)malloc(sizeof(LNode));
L->next = NULL;
LNode* r = L;
int x;
while (true)
{
cin >> x;
LNode *p = (LNode *)malloc(sizeof(LNode));
p->data = x;
r->next = p;
r = p;
if (cin.get() == '\n')break;
}
r->next = NULL;
return L;
}
int main()
{
cout << "头插法创建单链表"<<endl ;
LinkList L= createHead();
print(L);
cout << "尾插法创建单链表" << endl;
LinkList M = createTail();
print(M);
}