线性表-3-单链表的头插法与尾插法创建

#include 
#include 
using namespace std; 

typedef struct LNode{
     
	int data;
	struct LNode *next;
}LNode;

/*尾插法*/ 
void createLNodeR(LNode *&L,int arr[],int n){
     
	LNode *r,*s;
	int i;
	
	L = (LNode*)malloc(sizeof(LNode));
	L->next = NULL;
	
	r = L;
	
	for(i=0;i<n;i++){
     
		s = (LNode*)malloc(sizeof(LNode));
		s->data = arr[i];
		r->next = s;
		r = r->next;
	}
	r->next = NULL;
}

/*头插法*/
void createLNodeL(LNode *&L,int arr[],int n){
     
	LNode *s;
	int i;
	
	L = (LNode*)malloc(sizeof(LNode));
	L->next = NULL;
	
	for(i=0;i<n;i++){
     
		s = (LNode*)malloc(sizeof(LNode));
		s->data = arr[i];
		s->next = L->next;
		L->next = s;
	}
}  

int main(int argc, char** argv) {
     	
	int arr[4] = {
     1,2,3,4};
	LNode *L,*l;
	createLNodeL(L,arr,4);
	l=L;
	for(int i=0;i<6;i++){
     
		cout<<l->data<<"..";
		l = l->next;
	}
	return 0;
}

你可能感兴趣的:(线性表-3-单链表的头插法与尾插法创建)