/**
* 单链表
* 时间: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