1. 程式人生 > >c語言實現連結串列

c語言實現連結串列

c語言的動態記憶體管理函式實現動態記憶體管理;

1、malloc() 函式

void *malloc(unsigned int size);

分配一塊長度為size位元組的連續空間,並將該空間的首地址作為函式的返回值。

2、calloc()函式

void *calloc(unsigned int n, unsigned  int size);

分配一塊長度為n*size位元組的連續空間,並將該空間的首地址作為函式的返回值。

3、free()函式

void free(void *block);

釋放分配給指標變數block的動態空間。

程式碼:

#include <stdio.h>
#include <stdlib.h>
#define N 4 

struct node{
	int data;
	struct node *next;
}; 

int main(int argc, char *argv[]) {
	struct node *create_node(void);
	struct node *create_list(int);
	void out_list(struct node *);
	struct node *head=NULL;
	head=create_list(N);
	out_list(head);
	return 0;
}

//建立節點 
struct node *create_node(void){
	struct node *p;
	p=(struct node *)calloc(1,sizeof(struct node));
	scanf("%d",&(p->data));
	p->next=NULL;
	return p;
}

//建立連結串列 
struct node *create_list(int n){
	struct node *new,*head,*p;
	int i;
	if(n>=1){
	new=create_node();
	head=new;
	p=new;	/*p指向連結串列最後一個節點*/
	}
	for(i=2;i<=n;i++){
		new=create_node();
		p->next=new;
		p=new;
	}
	if(n>=1){
		return head;
	}
	else{
		return NULL;
	}
}

//輸出連結串列 
void out_list(struct node *head){
	struct node *p;
	if(head!=NULL){
		p=head;
		while(p!=NULL){
			printf("%d",p->data);
			p=p->next;
		}
	}
} 

//刪除節點p 
struct node *delete(struct node *head,struct node *P){
	struct node *q;
	if(p==NULL){
		return head;
	}
	if(p==head){
		head=head->next;
	}
	else{
		q=head;
		while(q->next!=p){
			q=q->next;
		}
		q->next=p->next;
	}
	free(p);
	return head;
}

//查詢data=x的節點 
struct node *find(struct node *head,int x){
	struct node *q;
	q=head;
	while(p!=NULL&&p->data!=x){
		p=p->next;
	}
	if(p==NULL){
		return NULL;
	}
	else{
		return p;
	}
} 

注意:C語言中,%c前面的空格就是用來遮蔽空白符(空格、換行符、製表符的。對於scanf()而言,%c是個較為特殊的說明符。 %c前沒空格,scanf()將讀取標準輸入流中的第一個字元,%c前有空格,scanf()則讀取標準輸入流中第一個非空白字元。