我是靠谱客的博主 曾经钢铁侠,最近开发中收集的这篇文章主要介绍c语言实现两个递增链表的差集(15),觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

在这里插入图片描述
终于来到了这一系列的最后一题了,明天终于可以做新的题目了,好期待~

这道题就是多了一个求链表长度,我们在链表的结构体中将其定义一下即可,然后在删除节点的时候别忘记了链表长度减1

代码

#include<stdio.h>
#include<stdlib.h>


typedef struct node
{
	int data;
	struct node * next;

}Node;

typedef struct list
{
	Node* head;
	Node* tail;
	int length;

}List;



void Init_list(List* L)
{
	Node* first = (Node*)malloc(sizeof(Node));
	if(!first)
		printf("wrong!n");
	first -> data = 0;
	first -> next = NULL;
	L->head = L->tail = first;

	int size_list;

	printf("please enter list length: ");
	scanf("%d",&size_list); //scanf里面不能写类似于printf中打印字符串的语句

	L->length = size_list;

	for(int i = 0; i< size_list; i++)
	{
		Node* new = (Node*)malloc(sizeof(Node));
		scanf("%d",&new -> data); //这个语句注意一下

		new -> next = NULL;
		L->tail -> next = new;
		L->tail = new;

	}


}


void chaji(List* l1, List l2)
{
	Node *p, *q,*save,*prev;
	p = l1->head->next;  q = l2.head->next; prev = l1->head;
	while(p && q)
	{
		if(p->data == q->data)   //删除节点
		{
			p = p -> next;
			q = q-> next;
			prev -> next = p;
			l1->length --;
		}
		else if(p->data > q->data)
		{
			q = q->next;
			
		}
		else  //当当前的都小于它的时候,后面的肯定都小
		{
			prev = p;
			p = p->next;

		}
	} 

}


void print_list(List L)
{
	Node* p;
	p = L.head->next;

	while(p != NULL)
	{
		printf("%d ",p->data);
		p = p -> next;
	}

	printf("n");
}


int main(int argc, char const *argv[])
{
	List l1,l2;

	Init_list(&l1);
	Init_list(&l2);

	chaji(&l1,l2);

	printf("After opertion: ");
	print_list(l1);
	printf("l1 链表中含有的元素为 %d 个n", l1.length);

	return 0;
}

运行截图:

最后

以上就是曾经钢铁侠为你收集整理的c语言实现两个递增链表的差集(15)的全部内容,希望文章能够帮你解决c语言实现两个递增链表的差集(15)所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(64)

评论列表共有 0 条评论

立即
投稿
返回
顶部