示例代码注重这里p1的作用
以下代码是用尾插法添加结点
#include <stdio.h>
#include <stblib.h>
#define N sizeof (STU)
typedef struct stu
{
int num;
char name[20];
} STU, * PSTU;
PSTU creat (PSTU head) //尾插法添加结点
{
PSTU head, p1, p2;
head = p1 = (PSTU) malloc (N); //p1的作用相当于将之后生成的结点链接到一起
p2 = (PSTU) malloc (N);
printf ("Please input the num(0 to quit), name:\n");
scanf ("%d %s", &p2->num, p2->name);
while (p2->num != 0)
{
p1->next = p2;
p1 = p2;
p2 = (PSTU) malloc (N);
printf ("Please input the num(0 to quit), name:\n");
scanf ("%d %s", &p2->num, p2->name);
}
p1->next = NULL;
free (p2);
return head;
}
第二个代码是合并2个升序链表#include <stdio.h>
#include <stdlib.h>
#define N sizeof (DATA)
typedef struct data
{
int data1;
struct data * next;
} DATA, * PDATA;
PDATA creat (void);
void print (PDATA head);
int count (PDATA head);
PDATA combine (PDATA head1, PDATA head2);
int main (void)
{
PDATA head1, head2, head3;
int n1, n2;
puts ("请输入第一个数列");
head1 = creat ();
n1 = count (head1);
puts ("请输入第二个数列");
head2 = creat ();
n2 = count (head2);
puts ("两个数列和到一起:");
head3 = combine (head1, head2);
print (head3);
return 0;
}
PDATA creat (void)
{
PDATA head, p1, p2;
head = p1 = (PDATA) malloc (N);
p2 = (PDATA) malloc (N);
printf ("请输入一个升序序列(0退出)");
scanf ("%d", &p2->data1);
while (p2->data1 != 0)
{
p1->next = p2;
p1 = p2;
p2 = (PDATA) malloc (N);
scanf ("%d", &p2->data1);
}
p1->next = NULL;
free (p2);
return head;
}
void print (PDATA head)
{
PDATA p = head;
p = p->next;
while (p)
{
printf ("%4d", p->data1);
p = p->next;
}
printf ("\n");
}
int count (PDATA head)
{
int n = 0;
PDATA p = head;
p = p->next;
while (p)
{
n++;
p = p->next;
}
return n;
}
//这里注重pc的作用
PDATA combine (PDATA head1, PDATA head2)
{
PDATA pa = head1;
PDATA pb = head2;
PDATA pc = head1;
pa = pa->next;
pb = pb->next;
while (pa && pb)
{
if (pa->data1 < pb->data1)
{
pc->next = pa;
pc = pa;
pa = pa->next;
}
else
{
pc->next = pb;
pc = pb;
pb = pb->next;
}
}
pc->next = pa ? pa : pb;
return head1;
}