你好
这是我的代码
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
typedef struct Node
{
int data;
struct Node *next;
}NODE,*PNODE;
void Delete(PNODE Head,int pos)
{
int i=0;
PNODE p=Head;
while(p&&(i<pos-1))
{
p=p->next;
i++;
}
if(p==NULL||i>pos-1)
{
printf("错误\n");
exit(-1);
}
PNODE q=p->next;
p->next=q->next;
free(q);
q=NULL;
}
void insert(PNODE Head,int pos,int val)
{
int i=0;
PNODE p=Head;
while((NULL!=p)&&(i<pos-1))
{
p=p->next;
i++;
}
if(p==NULL||i>pos-1)
{
exit(-1);
}
PNODE q=(PNODE)malloc(sizeof(NODE));
q->data=val;
q->next=p->next;
p->next=q;
}
PNODE create(int a)
{
int len;
int i;
int val;
PNODE list;
PNODE Head=(PNODE)malloc(sizeof(NODE));
if(Head==NULL)
{
printf("Memory allocation failure");
exit(-1);
}
else
{
PNODE tail=Head;
Head->next=NULL;
printf("please input the length of list: ");
for(i=0;i<a;i++)
{
PNODE p=(PNODE)malloc(sizeof(NODE));
if(p==NULL)
{
printf("memroy allocation failure");
exit(-1);
}
else
{
printf("please input the value of the %d list:",i+1);
scanf("%d",&val);
p->data=val;
tail->next=p;
p->next=NULL;
tail=p;
}
}
}
return Head;
}
void print(PNODE Head)
{
PNODE p;
if(!Head->next)
{
printf("the list is empty");
exit(-1);
}
p=Head->next;
while(p)
{
printf("%d\t",p->data);
p=p->next;
}
printf("\n");
}
struct Node* inter_link(struct Node* chain1,int
a,struct Node* chain2,int b)
{
int temp;
struct Node*head,*p1,*p2,*pos;
if(a>=b){
head=p1=chain1;
p2=chain2;
}else{
head=p1=chain2;
p2=chain1;
temp=a;
a=b;
b=temp;
}
pos=head;
while(p2!=NULL)
{
p1=p1->next;
pos->next=p2;
pos=p2;
p2=p2->next;
pos->next=p1;
pos=p1;
}
return head;
}
void inversion(PNODE Head)
{
PNODE p,q,pr;
p=Head->next;
q=NULL;
Head->next=NULL;
while(p)
{
pr=p->next;
p->next=q;
q=p;
p=pr;
}
Head->next=q;
}
void sort(struct Node *p,int m)
{
int i,j,t;
struct Node *k;
k=p;
for(i=0;i<m-1;i++)
{
for(j=0;j<m-i-1;j++)
{
if(p->data>(p->next)->data)
{
t=p->data;
p->data=(p->next)->data;
(p->next)->data=t;
}
p=p->next;
}
p=k;
}
}
int main()
{
PNODE Head,tab,boy;
int a,b,h;
scanf("%d",&a);
Head=create(a);
printf("this is the list:\n");
print(Head);
scanf("%d",&b);
tab=create(b);
print(tab);
inversion(Head);
printf("inverted list:\n");
print(Head);
printf("insert3:\n");
Head=inter_link(Head,a,tab,b);
print(Head);
insert(Head,3,999);
print(Head);
h=a+b;
Delete(Head,3);
print(Head);
//sort(boy,h);
//print(boy);
return 0;
}
为什么出现145368这个东西
我的问题是 为什么会出现这串数字
这是因为两个链表都带有头节点的原因。
在inter_link 方法中,p1=头节点,p2=头节点,while(p2!=NULL) 过程中,post->next=p2,表示post->next=头节点。
你是不是打算把头节点去掉?
这个方法中修改如下:
struct Node*head, *p1, *p2, *pos;
if (a >= b) {
head = p1 = chain1;
p2 = chain2->next; // attention!!!!!!!!!!!!!!!!
}
else {
head = p1 = chain2;
p2 = chain1->next; // attention!!!!!!!!!!!!!!!!
temp = a;
a = b;
b = temp;
}
结果如下: