您的位置:首页 > 其它

单链表的基本操作

2013-11-21 08:58 295 查看
#include <stdio.h>
#include <stdlib.h>
#include "list.h"

typedef struct list {
    int data;
    struct list *next;
} LIST;

LIST* createListRear(int *a, int len);

LIST* createListHead(int *a, int len);

LIST* findMiddleElement(LIST *head);

LIST* reverseList(LIST *head);

void printList(LIST *head);

int main()
{
	int a[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
	int len = sizeof(a) / sizeof(int);
	LIST *list;
	LIST *middle;
	LIST *reversedList;

	list = createListRear(a, len);
	// list = createListHead(a, len);
	printList(list);

	printf("\n***************************\n");
	reversedList = reverseList(list);
	printList(reversedList);

	// middle = findMiddleElement(list);
	// printf("middle element: %d\n", middle->data);

	return 0;
}

/* reverse a single linked list */
LIST* reverseList(LIST *head)
{
	LIST *a, *b;
	LIST *curNode;

	if ( NULL == head ) {
		printf("null list.\n");
		return NULL;
	}
	
	curNode = head->next;	
	if ( NULL == curNode ) return NULL;
	head->next = NULL;

	while ( curNode != NULL ) {
		a = curNode->next;
		curNode->next = head->next;
		head->next = curNode;	
		curNode =a;
	}

	return head;
}

/* find the middle element in single list */
LIST* findMiddleElement(LIST *head)
{
    LIST *a, *b;

    if ( NULL == head ) return NULL;
	if ( NULL == head->next ) return NULL;

    a = b = head->next;

    while ( b->next != NULL && b->next->next != NULL ) {
		a = a->next;
		b = b->next->next;
    }

	return a;
}

LIST* createListRear(int *data, int len)
{
	LIST *head, *rear, *newNode;
	int i;

	if ( data == NULL || len == 0 ) {
		printf("null data.\n");
		return NULL;
	}

	if ( (head = (LIST *)malloc(sizeof(LIST))) == NULL ) {
		return NULL;
	}

	head->data = len;
	head->next = NULL;	
	rear = head;

	for ( i = 0; i < len; i++ ) {
		if ( (newNode = (LIST *)malloc(sizeof(LIST))) == NULL ) {
			return NULL;
		}
		newNode->data = data[i];
		newNode->next = rear->next;
		rear->next = newNode;
		rear = newNode;
	}

	return head;		
}

LIST* createListHead(int *a, int len)
{
	LIST *head;
	LIST *newNode;
	int i;

	if ( a == NULL || len == 0 ) {
		printf("null data.\n");
		return NULL;
	}

	if ( (head = (LIST *)malloc(sizeof(LIST))) == NULL ) {
		printf("memory not available.\n");
		return NULL;
	}
	head->data = len;
	head->next = NULL;

	for ( i = 0; i < len; i++ ) {
		if ( (newNode = (LIST *)malloc(sizeof(LIST))) == NULL ) {
			printf("memory not available.\n");
			return NULL;
		}

		newNode->data = a[i];
		newNode->next = head->next;
		head->next = newNode;

	}

	return head;

}

void printList(LIST *head)
{
	LIST *curNode;

	curNode = head;
	printf("List print: ");
	while ( curNode->next != NULL ) {
		curNode = curNode->next;
		printf("%d\t", curNode->data);
	}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: