单链表的基本操作

#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);
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值