建立两个单向链表,从第一个链表中删除第二个链表中已存在的节点



#include<stdio.h>
#define LEN sizeof(node)
#define LEN2 sizeof(node2)
typedef struct dataa
{
 int num;
 struct dataa *next;
}*List, node;
typedef struct datab
{
 int num;
 struct datab *next;
}*List2, node2;
List phead;
List2 qhead;
List creat(int n)
{
 int i = 0;
 List r, s, head;
 head = (List)malloc(LEN);
 head->next = NULL;
 r = (List)malloc(LEN);
 while(i++<n){
  s = (List)malloc(LEN);
  printf("请输入数据:\n");
  scanf("%d", &s->num);
  s->next = head->next;
  head->next = s;
  r = s;
 }
 return head;


}
List2 creat2(int n)
{
 int i = 0;
 List2 r, s, head;
 head = (List2)malloc(LEN);
 head->next = NULL;
 r = (List2)malloc(LEN);
 while(i++<n){
  s = (List2)malloc(LEN);
  printf("请输入数据:\n");
  scanf("%d", &s->num);
  s->next = head->next;
  head->next = s;
  r = s;
 }
 return head;


}
void print()
{
 List p;
 for(p = phead->next;p!=NULL;p = p->next){
  printf("%d\n", p->num);
 }

void deletes()
{
List p = phead->next, t, pre = phead;
List2 q;
  while(p){
  q = qhead->next;
  while(q){
  if(p->num == q->num){
  t = p;
  pre->next = p->next;
  p = pre;
  free(t);
  }
  q = q->next; 
 
  pre = p;
  p = p->next;
 }
 return phead;
}
int main()
{
 int n, m;
 printf("请输入第一个链表节点个数 :\n");
 scanf("%d", &n);
 phead = creat(n);
 printf("请输入第二个链表节点个数 :\n");
 scanf("%d", &m);
 qhead = creat2(m);
 deletes();
 printf("删除后:\n");
 print();
 
}

猜你喜欢

转载自blog.csdn.net/qiangshuting/article/details/80535858