#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);
}
带头结点非循环单链表
最新推荐文章于 2023-12-17 21:43:04 发布