创建链表 -- C语言

这个问题很简单,只有一个地方处理需要很注意:首节点的处理和尾结点处理

假设:head 为链表头,p 指向链表当前处理的节点。这个时候,如果只有一个节点,那么特征是: head->next = NULL,我们可以通过这个条件判断是否是头结点处理,处理完 p=head,但是下一个循环会发现的时候 head->next 依然是空;所以这里需要一点小技巧来进行处理了,我们让 p->next = head,这样头结点就是一个换了,下一次判断的时候,head->next != NULL,说明head已经复制,需要建立一个新的节点了,后面有了新的节点后,用 p->next = new node 就可以解开这个环了;但是信心的同学会发现,如果就只有一个元素,那不是打环了吗?怎么办?我们通过尾结点的处理来解决这个问题,当有一个节点的时候 head->next = head,发生退出,退出后,我们让 p->next = NULL; 这样就让 head->next = NULL 了,环就解开了

代码实现

list.c


#include <stdio.h>
#include <stdlib.h>
#include "list.h"


void dumpList(st_dataNode * head){
	if(NULL == head){
		return;
	}

	st_dataNode * p = NULL;
	
	printf("========= Dump List %p ===========\n\t", head);
	p = head;
	while (NULL != p){
		printf(" %d ", p->data);
		p = p->next;
	}
	printf("\n");
	printf("===================================\n");
}

st_dataNode* createList(st_dataNode* head, int * array, int size){

	if(NULL == array){
		printf("%s para error\n", __func__);
		return NULL;
	}

	int i = 0;
	unsigned int st_size = sizeof(st_dataNode); 
	st_dataNode * p = NULL;
	st_dataNode * q = NULL;

	if(NULL == head){
		head = (st_dataNode *) malloc(st_size);
		head->next = NULL;
	}

	/*初始化头结点*/
	for(i = 0; i < size; i++){
		if(NULL == head->next){ /*首节点*/
			head->data = array[i];
			p = head; 
			/* 注意这里是为了区分首节点和中间节点
			 * 如果只有一个节点,会在循环外面,修复p->next = NULL*/
			p->next = head; 
		} else { /*中间节点*/
			/* 创建节点 */
			q = (st_dataNode *) malloc(sizeof(st_dataNode));
			q->data = array[i];
			q->next = NULL;				

			/*连接节点*/
			p->next = q;
			p = q;
		}			
	}

	/*尾结点*/
	p->next = NULL;

	return head;
}



void testCreateNode(void){
	/*初始化input数据*/
	int input[10] = {22,32,19,53,0,47,29,116,4,6};
	ghead = NULL;

	ghead = createList(ghead, input, 10);

#ifdef DEBUG
	dumpList(ghead);
#endif

	return;
}



list.h

#ifndef __LIST_H__
#define __LIST_H__

#define SUCCESS		0
#define PARAM_ERR	-1

typedef struct dataNode {
	int data; /*这里可扩展为任何数据,暂时简单就用一个 int*/
	struct dataNode * next;
} st_dataNode;

struct dataNode * ghead;

st_dataNode* createList(st_dataNode* head, int * array, int size);
void dumpList(st_dataNode * head);


void testCreateNode(void);

#endif

listMain.c


#include <stdio.h>
#include "list.h"



int main(int argc, char ** argv){

	testCreateNode();

	return SUCCESS;
}

调试编译

gcc listMain.c list.c -o a.exe -DDEBUG

调试输出

========= Dump List 0x1205010 ===========
         22  32  19  53  0  47  29  116  4  6
===================================
发布了191 篇原创文章 · 获赞 43 · 访问量 26万+

猜你喜欢

转载自blog.csdn.net/leoufung/article/details/104332933
今日推荐