链表周测

这篇博客介绍了链表的各种操作,包括如何在有序链表中插入1~20的数保持有序,如何反转链表,删除链表中的重复节点,根据输入整数移动链表节点,找出链表的倒数第k个节点,以及仅遍历一次链表找到中间节点。这些操作涵盖了链表的基本操作和常见的面试问题。
摘要由CSDN通过智能技术生成

1.建立一个单向有序链表,初始包含1 5 7 16输入一个1~20的数,将其插入其中并使链表依然有序

扩展:输入n个数,使其依然有序。

#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
   
	int data;
	struct Node *next;
}Node;
Node *create()
{
   
	Node *head,*r,*p;
	head=(Node *)malloc(sizeof(Node));
	head->next =NULL;
	r=head;
	printf("初始化链表,请输入4个数字:");
	for(int i=1;i<=4;i++)
	{
   
		int x;
		scanf("%d",&x);
		p=(Node *)malloc(sizeof(Node));
		p->data =x;
		r->next =p;
		r=p;
	}
	r->next =NULL;
	return head; 
}
Node *insert(int n)
{
   
	Node *head,*pre,*p;
	head=create();
	pre=head;
	int x,i;
	printf("输入你要插入的数字:");
	for(i=1;i<=n;i++)
	{
   	
		scanf("%d",&x);
		p=(Node *)malloc(sizeof(Node));
		p->data =x;
		pre=head->next ;
		if(pre->data >=x)
		{
   
			p->next =head->next ;
			head->next =p;
		}
		else
		while(pre->next )
		{
   
			if(pre->data <x&&pre->next ->data>=x)
			{
   
				p->next =pre->next ;
				pre->next =p;
				break;
			}
			else
				pre=pre->next ;
		}
		if(pre->next ==NULL)
			{
   
				pre->next =p;
				p->next =NULL;
			}
		pre=head->next ;;	
	}
	return head;
}
int main(void)
{
   
	Node *head;
	int n;
	printf("请输入要插入多少个数字:"); 
	scanf("%d",&n);
	head=insert(n);
	head=head->next ;
	printf("插入后的链表结果:");
	while(head)
	{
   
		printf("%d ",head->data );
		head=head->next ;
	}
}
运行结果
请输入要插入多少个数字:5
初始化链表,请输入4个数字:1 5 9 16
输入你要插入的数字:-5 -1 4 0 17
插入后的链表结果:-5 -1 0 1 4 5 9 16 17
--------------------------------
Process exited after 24.78 seconds with return value 0
请按任意键继续. . .

2反转一个单链表。

示例:

输入: 1 2 3 4 5
输出: 5 4 3 2 1

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值