单链表

/**
* 单链表
* 时间:2016-3-4 22:43
* 功能:创建,打印,删除,测长
*/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
 
 #define OK                 1
#define ERRoR            0
#define OVERFLOW  -1

typedef int Status;
typedef int ElemType;
typedef struct LNode
{
	Status data;
	struct LNode* next;
}LNode,* ListNode;

/**
* 创建单链表
* singList :声明的单列表;array:数组;arrlength:数组长度
*/
Status creatList(ListNode &singList , int array[] , int arrlength)
{
	ListNode head, p;
	head = (ListNode)malloc( sizeof(LNode) );
	if(!head)
	{
		return OVERFLOW ;
	}
	head->data = 0;
	head->next = NULL;
	p = head;	//把head赋值给p,操作p等于操作head;
	for (int i = 0; i < arrlength; ++i)
	{
		ListNode temp = (ListNode)malloc( sizeof(LNode) );
		temp->data = array[i];
		temp->next = NULL;
		p->next = temp;   
		p = temp;        //把temp赋值给p,操作p等于操作temp;
	}
	singList = head;
	return OK ;
}

/**
* 打印单链表
*/
void printList(ListNode singList)
{
	ListNode node = singList->next;
	while( node != NULL)
	{
		cout << node->data << " " ;
		node = node->next;
	}
	cout << endl;
}

/**
* 测单链表长度
*/
int getListLength(ListNode singList)
{
	int listLength = 0;
	ListNode node = singList->next;
	while( node != NULL)
	{
		++listLength;
		node = node->next;
	}
	return listLength;
}

/**
* 删除单链表节点
*/
void delListNode(ListNode singList , int data)
{
	ListNode node = singList->next;
	ListNode temp;
	while(node->data != data && node->next != NULL)
	{
		temp = node;
		node = node->next;
	}
	if(node->data == data)
	{
		temp->next = node->next;
		//cout << node->data << endl;  // 6
		free(node);
		//cout << node->data << endl;  // 0
	}else{
		cout << "sorry ! not found the date:" << data << endl;
		//cout << node->data << endl ;     //链表最后一个数:9
	}
}

 int main(int argc, char const *argv[])
 {
 	int array[] = {1,2,3,4,5,6,7,8,9};
 	int arrlength = sizeof(array) / sizeof(int) ;
 	ListNode singList;
 	creatList(singList , array, arrlength);
 	cout << "这个单链表的长度为:" << getListLength(singList) << endl;
 	printList(singList);

 	//删除单链表的值为data的节点
 	delListNode(singList,6);
 	printList(singList);
 	delListNode(singList,16);
 	printList(singList);
 	return 0;
 }

结果:
这个单链表的长度为:9
1 2 3 4 5 6 7 8 9 
1 2 3 4 5 7 8 9 
sorry ! not found the date:16
1 2 3 4 5 7 8 9 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值