编写一个程序将一个头结点指针为pa的单链表A分解成两个单链表A和B,其头结点指针分别为pa和pb,使得A链表中含有原链表A中序号为奇数的元素,而链表B中含有原链表A中序号为偶数的元素,且保持原来的相对顺序。
我的程序:
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node * next;
};
struct node * list(struct node *head);
void display(struct node *head);
void main()
{
struct node * head=NULL,* p1,*p2,*pb;
//int data;
printf("建立单向链表/n");
head=list(head);
display(head);
p1=head;
p2=p1->next;
pb=p2;
while(p1!=NULL)
{
p1->next=p2->next;
p1=p1->next;
p2->next=p1->next;
p2=p2->next;
}
printf("输出单向链表a/n");
display(head);
printf("输出单向链表b/n");
display(pb);
}
struct node * list(struct node *head)//链表输入//
{
int n;
struct node * p,* p1;
printf("读入结点数据(以0结束)");
scanf("%d",&n);
p=(struct node *)malloc(sizeof(struct node));
p->data=n;
p->next=NULL;
p1=p;
head=p;
scanf("%d",&n);
while(n!=0)
{
p=(struct node *)malloc(sizeof(struct node));
p->data=n;
p->next=NULL;
p1->next=p;
p1=p1->next;
scanf("%d",&n);
}
return head;
}
void display(struct node * head)//链表输出//
{
struct node *p;
p=head;
while(p!=NULL)
{
printf("[%d]-->",p->data);
p=p->next;
}
printf("NULL/n");
}
在执行主函数的while循环时出错,希望高手指点。
谢谢