存储结构
一个节点node包括一个数据域和一个指针域,指针域指向下一个node节点的地址
typedef struct node{
datatype data;
struct node * next;
}LNode;
初始化函数
声明一个lnode类型的指针变量head,对head分配内存空间,将数据域赋值为0,指针域赋值为null
LNode *init_linklist() {
LNode *head;
head=(LNode*)malloc(sizeof(LNode));
head->data = 0;
head->next = NULL;
return (head);
}
插入函数
循环给变量p分配内存空间,采用后插法连接节点,并返回节点个数
int insert(LNode *head) {
datatype e;
LNode *p;
int i = 0;
scanf_s("%d",&e);
while (e != 0) {
p = (LNode*)malloc(sizeof(LNode));
p->data = e;
p->next = NULL;
head->next= p;
head = p;
scanf_s("%d", &e);
i++;
}
return(i);
}
逆置函数
声明三个lnode类型的指针变量p,q和j,让p,q都指向head的地址,遍历head,是头指针指向最尾,在输入3个数时候,通过遍历p在p->next=head时停止遍历,而后将head=p->next,j=head实现将head指针实现逆置。
p的next指向 ,p的位置 | head的next指向,head的位置 |
---|---|
p->next->next | head->next |
p->next | head->next |
p | head->next |
LNode* reverse(LNode *head) {
LNode *p,*q,*j;
p = head;
q = p;
while (head->next!= NULL)
{
head = head->next;
}
j = head;
while (head!=p)
{
while (p->next!=head)
{
p=p->next;
head->next=p;
}
if (q->next==head)
{
head->next = p;
p->next = NULL;
}
head = p;
p = q;
}
return j;
}
当p与初始q重合时
此时诺将p的地址赋予head则p与head重合,p->next永远无法=head,无限循环。因此当q->next=head时,将前面head->next指向p,放回尾节点j,循环结束
主函数
int main() {
int i=1;
LNode *head,*p;
head=init_linklist();
i=insert(head);
p=reverse(head);
printf("%d",i);
while (p!=NULL)
{
printf("%d", p->data);
p=p->next;
}
return 0;
}