单链表的创建-尾插法
#include<iostream>
#include<cstdlib>
using namespace std;
struct LNODE
{
int val;
LNODE *pnext;
};
LNODE* initListEnd(int arr[],int n) //尾插法,head:目标链表头结点,arr[]:插入值存放数组,n:数组长度
{
LNODE *head = (LNODE*)malloc(sizeof(LNODE));
head->pnext = NULL;
LNODE *tmpNode; //临时结点用来存放当前arr的值
LNODE *endNode; //始终指向目标链表尾端的节点
endNode = head; //此时目标链表只有头结点
for(int i = 0 ; i < n ; ++i ) //将arr[]中的值依次依次插入链表尾端
{
tmpNode = (LNODE*)malloc(sizeof(LNODE)); //为新结点申请空间
tmpNode->val = arr[i]; //新结点赋值
endNode->pnext = tmpNode; //目标链表尾指向新结点
endNode = endNode->pnext; //更新endNode使其指向目标结点尾端
}
endNode->pnext = NULL;
return head;
}
int main()
{
int n = 10;
int arr[n]={1,2,3,4,5,6,7,8,9,0};
LNODE *head;
head = initListEnd(arr,n);
LNODE *tNode = head->pnext; //创建临时结点tNode依次输出链表各结点的值
while(tNode->pnext != NULL)
{
cout<<tNode->val<<" "<<endl;
tNode = tNode->pnext;
}
cout<<tNode->val<<endl; //最后一个结点pnext已经为NULL了,所以循环中没有输出它,需要单独输出
return 0;
}
网友评论