C语言链表编程题

输入文件的第一行有两个整数n,q,分别表示初始链表中元素个数和对链表操作的次数,第二行有
n个整数,表示初始链表的元素,保证这些数字不超过int表示的范围。
接下来q行,每行可能为如下两个操作之一:
1 a b表示在第a个元素后面插入值为b的元素,
2 a表示将链表中第a个元素删除,如果a大于当时链表长度,则忽略此操作

如:

输入

3 3
1 2 3
1 1 4
1 2 5
2 2

输出(每个元素后面需要跟一个空格)

1 5 2 3
 

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

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

struct node *head,*tail,*node;


struct node *create_linklist(int n)
{
    head = (struct node *)malloc(sizeof(struct node));
	tail = head;
	for (int i = 0; i < n; i++) {
	 node = (struct node *)malloc(sizeof(struct node));
		scanf("%d",&node->data);
		tail->next = node;
		tail = node;	
	}
	 tail->next = NULL;
	 return head;
}

void insert_node(int pos, int data)
{
    struct node *pre;
	pre = head;
	int i = 0;
	struct node *p = (struct node *)malloc(sizeof(struct node));
	if (pos == 0) {
		p->data = data;
	    p->next = head;
	    head = p;
	} else {
	    while (i < pos) {
		    pre = pre->next;
			i++;		
	}
			p->data = data;
		    p->next = pre->next;
		    pre->next = p;
		    if (tail->next  == NULL)
				tail = p;
	}
}

void delete_node(int pos)
{
    struct node *pre, *p;
	pre = head;
	int i = 0;
	if (pos == 0) {
	   head = head->next;
		free(pre);
	} else {	
	    while (i < pos -1) {
		      pre = pre->next;
			  i++;	
		}
		 p = pre->next;
		 pre->next = p->next;
		 if (p->next == NULL)
			 tail = pre;
		     free(p);
	}	
}

void print_linklist(void)
{
    struct node *p;
	p = head;
	while (p->next) {
	 p = p->next;
	 printf("%d ", p->data);	
	}
	if (p == NULL)
	  printf(" ");
}

int main(int argc, char *argv[])
{
   int n, q;
	scanf("%d %d", &n, &q);
	head = create_linklist(n);
	int flag, pos, data;
	for (int i = 0; i < q; i++) {
	scanf("%d", &flag);
	if (flag == 1) {
	scanf("%d%d", &pos, &data);
    insert_node(pos, data);
	} else {
	delete_node(pos);
	}
	}
    print_linklist();
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值