创建结构体:
typedef struct student
{
int data;
struct student *next;
}node;
int len = sizeof(node); // 记录大概长度
创建链表:
node *create_node()
{
node *head,*p,*s;
int cycle = 1,x;
head = (node*)malloc(sizeof(node)); // 开辟空间
p = head;
while(cycle)
{
scanf("%d",&x);
if(x != 0) // 以0作为输入结束标志
{
s = (node*)malloc(sizeof(node));
s -> data = x;
p -> next = s; // p的next指向s
p = s; // 将p后移
//s->next=NULL;
}
else
cycle = 0;
}
head = head -> next; // 由于前面设置问题,从下一位开始为我们输入的值
s -> next = NULL; // 尾部封口
return head;
}
输出函数:
void print(node *head)
{
node *p;
p = head;
while (p != NULL)
{
printf("%d\n", p -> data);
p = p -> next;
}
}
计算链表长度:?
int length_node(node *head)
{
int n = 0;
node *p;
p = head;
while (p != NULL)
{
n++;
p = p -> next;
}
return n;
}
删除函数(划重点):?
node* del(node *head, int num)
{
node *p, *s;
//p = s = (node *) malloc(len);
p = head;
while (p -> next != NULL && p -> data != num)
{
s = p; // 记录p的前一位
p = p -> next;
}
if(p -> data == num)
{
if(p == head)
{
//s = head;
head = p -> next; // 头节点向后移
}
else
{
s -> next = p -> next;
}
free(p); // 释放空间
}
else
{
printf("无节点删除\n");
}
return head;
}
完整代码如下:?
#include <stdio.h>
#include <string.h>
#include <malloc.h>
typedef struct student
{
int data;
struct student *next;
}node;
int len = sizeof(node);
node *create_node()
{
node *head,*p,*s;
int cycle=1,x;
head=(node*)malloc(sizeof(node));
p=head;
while(cycle)
{
scanf("%d",&x);
if(x!=0)
{
s=(node*)malloc(sizeof(node));
s->data=x;
p->next=s;
p=s;
//s->next=NULL;
}
else
cycle=0;
}
head=head->next;
s->next=NULL;
return head;
}
void print(node *head)
{
node *p;
p = head;
while (p != NULL)
{
printf("%d\n", p -> data);
p = p -> next;
}
}
int length_node(node *head)
{
int n = 0;
node *p;
p = head;
while (p != NULL)
{
n++;
p = p -> next;
}
return n;
}
node* del(node *head, int num)
{
node *p, *s;
//p = s = (node *) malloc(len);
p = head;
while (p -> next != NULL && p -> data != num)
{
s = p; // 记录p的前一位
p = p -> next;
}
if(p -> data == num)
{
if(p == head)
{
//s = head;
head = p -> next;
//free(p);
}
else
{
s -> next = p -> next;
}
free(p); // 释放空间
}
else
{
printf("无节点删除\n");
}
return head;
}
int main()
{
node *head;
head = create_node();
printf("长度:%d\n", length_node(head));
print(head);
int num;
printf("要删除的数为:");
scanf("%d", &num);
print(del(head, num));
return 0;
}
|