链表

.可变数组存在的问题:
 .每次内存不够用都要花时间赋值前一段空间的内容
 .可能会遇到空间不够的情况
.解决方案
.不用复制,直接告诉下一块内存的位置,链接起来就能充分利用内存空间
.制作一个单向链表[licked-list.c]
.node2.h

#ifndef __NODE_H__
#define __NODE_H__

typedef struct _node
{
	int value;
	struct _node* next;
}Node;

typedef struct _list
{
	Node* head;
} List;


void add(List* list, int number);
void print(List* list);
int search(List* list, int number);
void remove_(List* list, int number);
void delete_linked_list(List* pList);

#endif

.function.c

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

//delete linked-list
void delete_linked_list(List* pList)
{
	Node* p;
	Node* q = NULL;
	for( p=pList->head; p;p=q->next )
	{
		q = p->next;
		free(p);
	}
}

//remove a number of linked-list
void remove_(List* pList, int number)
{
	//Find a number and remove it from linked-list
	Node* p;
	Node* q;
	for( q=NULL, p=pList->head; p; q=p,p=p->next)
	{
		if( p->value == number )
		{
			if( q )
			{
				q->next = p->next;
				free(p);
			}else{
				pList->head = p->next;
			}
		}
	}
}

void add(List* list, int number)
{
	//add to link_list
	Node* p = (Node*)malloc(sizeof(Node));
	p->value = number;
	p->next = NULL; 
	//find the last
	Node* last = list->head;
	if( last )
	{
		while( last->next )
		{
			last = last->next;
		}
		//attach
		last->next = p;
	}
	else
	{
		list->head = p;
	}
}

//print linked-list
void print(List* pList)
{
	//iterate through linked-list
	Node* p;
	for( p=pList->head; p; p=p->next )
	{
		printf("%d\t", p->value);
	}
	printf("\n");
}

//search number of linked-list
int search(List* pList ,int number)
{
	int isFound = 0;
	int result = -1;
	Node* p;
	for( p=pList->head; p; p=p->next )
	{
		if( p->value == number )
		{
			printf("Found number is %d\n", number);
			isFound = 1;
			break;
		}
	}
	if( isFound )
		result = number;
	return result;
}

.link-list2.c

#include <stdio.h>
#include <stdlib.h>
#include "node2.h"
/*
typedef struct _node{
	int value;
	struct _node* next;	
}Node;
*/

int main(int argc, char const *argv[])
{
	List list;
	list.head = NULL;
	int number;
	do{
		scanf("%d", &number);
		if( number != -1 )
		{
			add(&list, number);
		}
	}while( number != -1 );

	print(&list);

	delete_linked_list(&list);
/*
	int goal;
	scanf("%d", &goal);
	remove_(&list, goal);
	print(&list);
*/
/*	int goal;
	scanf("%d", &goal);
	if( search(&list, goal) != -1 )
	{
		printf("Success!\n");
	}else{
		printf("Unsuccess!\n");
	}
	*/

	return 0;
}

.运行结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值