关注公众号程序猿从入门到入土查询更方便哦
头插法建立带头结点的单链表,读入要建立单链表的节点数,输入节点值(整型),打印输出链表。
输入:
5 //要插入的元素个数
1 2 3 4 5 //插入的元素
输出
5 4 3 2 1 //插入后输出的元素
#include<iostream>
#define RESULT int
#define OK 1
#define ERROR 0
using namespace std;
typedef struct Node {
int data = 0;
Node *next = NULL;
}LNode, *LinkList;
RESULT InitList(LinkList &L); //初始化链表
RESULT InsertData_Head(LinkList &L, int data); //头插
RESULT Output_LinkList(LinkList& L); //打印链表
int main() {
int n = 0;
cin >> n;
LinkList L = new LNode;
InitList(L);
for (int i = 0; i < n; i++) {
int a = 0;
cin >> a;
InsertData_Head(L, a);
}
Output_LinkList(L);
return 0;
}
RESULT InitList(LinkList &L) {
L = new LNode;
L->next = NULL;
return OK;
}
RESULT InsertData_Head(LinkList &L, int data) {
LinkList temp = new LNode;
temp->data = data;
if (L->next == NULL) {
L->next = temp;
return OK;
}
temp->next = L->next;
L->next = temp;
return OK;
}
RESULT Output_LinkList(LinkList& L) {
LinkList temp = L->next;
while (temp != NULL) {
cout << temp->data << endl;
temp = temp->next;
}
return OK;
}