带头结点非循环单链表


#include"stdio.h"
#include"malloc.h"

typedef struct Node
{
int data;
Node *next;
}Node;

void InitNode(Node *&p)
{
p = (Node *)malloc(sizeof(Node));
p->next = NULL;
}

// 头插法建立单链表
void createfromhead(Node *p)
{
int n;
Node *q,*r;
r = p->next;
printf("create list, input -1 to end:");
scanf("%d",&n);
while(n != -1)
{
q = (Node *)malloc(sizeof(Node));
q->data = n;
q->next = r;
r = q;
p->next = r;
scanf("%d",&n);
}
}

// 尾插法建立单链表
void createfromtail(Node *p)
{
Node *q, *r;
r = p;
int n;
printf("create list, input -1 to end:");
scanf("%d",&n);
while(n != -1)
{
q = (Node *)malloc(sizeof(Node));
q->data = n;
q->next = NULL;
r->next = q;
r = q;
scanf("%d",&n);
}
}

void display(Node *p)
{
Node *q;
q = p->next;
printf("The List: ");
while(q != NULL)
{
printf("%d ",q->data);
q = q->next;
}
printf("\n");
}

int lengthNode(Node *p)
{
int n = 0;
Node *q;
q = p->next;
while(q != NULL)
{
++n;
q = q->next;
}
return n;
}

void deleteNode(Node *p, int n, int &x)
{
int length ;
length = lengthNode(p);
int k = 0;
Node *q,*r;
if(n<=0 || n> length)
{
printf("The position is not suitable!\n");
}
else{
q = p;
while( k != (n-1))
{
q = q->next;
++k;
}
r = q->next;
q->next = r->next;
x = r->data;
free(r);
}
}

int insertNode(Node *p,int position,int x)
{
if(position<1 || position>lengthNode(p))
{
printf("The position is not suitable, insert failed!\n");
return 0;
}
Node *r, *q;
r = p->next;
int n = 1;
while(n!= position-1)
{
++ n;
r = r->next;
}
q = (Node *)malloc(sizeof(Node));
q ->data = x;
q ->next = r->next;
r->next = q;
return 1;
}

void main()
{
Node *p;
InitNode(p);
createfromhead(p); // createfromtail(p);
display(p);
int x;
deleteNode(p,2,x);
printf("The delete Node is %d\n",x);
display(p);
insertNode(p,2,7);
display(p);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值