单链表整理

// Sunnyworld.cpp : Defines the entry point for the console application.
//


#include "stdafx.h"
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include <assert.h>




typedef struct tagNode
{
int data;
struct tagNode *next;
}node;


node *creat(int n)
{
node *head = NULL;
node *p = NULL;
node *s = NULL;
head = (node*)malloc(sizeof(node));
if (!head) 
assert(0);
head->data = 0xFF;
p = head;

for(int i = 1; i <= n; i++)
{
s = (node*)malloc(sizeof(node));
if (!s) 
return head; 
s->data = i;
s->next = NULL;
p->next = s;
p = s;
}

return head;
}




void DestroyList(node *head)//h
{
node *p = NULL;
int num = 0;
while (head)
{
p = head;
head = head->next;
printf("\r\nfree node%i data = %i", num, p->data);
free( p );
num++;
}


}


void display(node*h)
{
node *p = h->next;

while (p != NULL)
{
printf("\r\n %i", p->data);;
p = p->next;
}

return ;
}


int GetLenth(node *h)
{
node *p = h->next;
int len  = 0;


while(p)
{
len++;
p = p->next;
}


return len;
}


int GetElem(node *head, int pos, int *e)
{
node *p = head->next;
int j = 1;
while(p && j < pos)
{
p = p->next; 
j++;
}
if (!p || j > pos) 
return -1;

*e = p->data;

return 0;
}


int ListInsert(node *head, int pos, int e)
{


node *p = head; int j = 0;
node *s = NULL;
while(p && j < pos - 1)
{
p = p->next; 
++j;
}
if (!p || j > pos -1 )
return -1;
s = (node*)malloc(sizeof(node));
if (!s) 
return -1;
s->data = e;
s->next = p->next;
p->next = s;
return 0;
}


int ListDelete(node *head, int pos, int *e)
{
node *p = head; 
int j = 0;
node *q = NULL;
while(p->next && j < pos -1)//跟插入算法的区别,插入算法只要前驱在就行,删除不仅要前驱在,被删除节点也要存在才行
{
p = p->next; 
++j;
}
if (!(p->next) || j > pos - 1) //pos < 1
return -1;
q = p->next;
p->next = q->next;
*e = q->data; 
free(q);
return 0;
}


int _tmain(int argc, _TCHAR* argv[])
{
int ret = 0;
node *head = NULL;
int data = 0;

head = creat(5);
if (!head) return -1;


//ListInsert(head, 1, 11);

int len = GetLenth(head);


//ListInsert(head, len + 2, 22);
//ListDelete(head, 6, &data);
GetElem(head, 1, &data);
printf("\r\n data = %i", data);
display(head);


DestroyList(head);
head = NULL;
display(head);

return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值