单链表尾插法(顺序表)实现代码

#include "stdafx.h"
#include
using namespace std;

//单链表结构体:

typedef struct LNODE * List;

struct LNODE {
int data;
List  next;

};

//头节点生成

LNODE * creat() {
LNODE *head=new LNODE;
head->next = NULL;
return head;

}

//根据初始数据建立单链表

LNODE * creatlist(int x, LNODE *head) {

if (head->next == NULL) {
List pNewNode = new LNODE;
pNewNode->data = x;
pNewNode->next = NULL;
head->next = pNewNode;
return head;//返回头节点
}
else {
List s = head->next;
while (s->next!=NULL) {
s = s->next;//s->next为空时,跳出循环,新建一个List 
}
List pNewNode = new LNODE;
pNewNode->data = x;
pNewNode->next = NULL;
s->next = pNewNode;
return head;//返回头节点
}

}

//打印单链表

void print(LNODE * head ){
List s = head->next;
while (s!= NULL){
cout << s->data << " ";
s = s->next;
}
};

int main()
{

LNODE * head=creat();
int x;
cin >> x; //单链表初始元素个数
int data[100];
for (int i = 0; i < x; i++)
{
cin >> data[i];
creatlist(data[i], head);
}

print(head);

}

你可能感兴趣的:(单链表尾插法(顺序表)实现代码)