删除链表的中间节点和a/b处的节点

题目

给定链表的头节点head,实现删除链表中间节点的函数和删除位于a/b处节点的函数。 当有偶数个节点时,删除两个中间节点的前一个,有奇数个节点时,删除中间节点。
删除a/b处的节点:链表1->2->3->4->5,假设a/b的值为r,如果r = 0,不删除任何节点。如果r在区间(0,1/5]上,删除节点1;依次类推;如果r>1,则不删除任何节点。
具体题目可参考原书

代码

#include<iostream>
using namespace std;

struct node {
	int value;
	node* next;
	node(int val)
	{
		value = val;
	}
};

node* removeMidNode(node* head)
{
	if (head == NULL || head->next == NULL)
		return head;
	if (head->next->next == NULL)
		return head->next;
	node* prev = head;
	node* cur = head->next->next;
	while (cur->next != NULL && cur->next->next != NULL)
	{
		prev = prev->next;
		cur = cur->next->next;
	}
	prev->next = prev->next->next;
	return head;
}

node* removeByRation(node* head, int a, int b)
{
	if (a < 1 || a > b)
		return head;
	int n = 0;
	node* cur = head;
	while (cur != NULL)
	{
		n++;
		cur = cur->next;
	}
	if (n == 1)
		head = head->next;
	if (n > 1)
	{
		n = ceil((double)(a * n) / (double)b);
		cur = head;
		while (--n != 1)
			cur = cur->next;
		cur->next = cur->next->next;
	}
	return head;
}

node* createList(int* in, int len)
{
	node* head = new node(in[0]);
	node* p = head;
	for (int i = 1; i < len; i++)
	{
		node* pNode = new node(in[i]);
		p->next = pNode;
		p = p->next;
	}
	p->next = NULL;
	return head;
}

void printList(node* pHead)
{
	cout << "Node of List:" << endl;
	if (pHead == NULL)
		cout << "NULL" << endl;
	while (pHead != NULL)
	{
		cout << pHead->value << " ";
		pHead = pHead->next;
	}
	cout << endl;
}

int main()
{
	int input1[] = { 1, 2, 3, 4, 5 };
	int input2[] = { 1, 2, 3, 4 };
	int input3[] = { 1, 2, 3, 4, 5, 6, 7 };
	int a = 5, b = 6;
	node* pHead1 = createList(input1, 5);
	node* pHead2 = createList(input2, 4);
	node* pHead3 = createList(input3, 7);
	node* p1 = removeMidNode(pHead1);
	node* p2 = removeMidNode(pHead2);
	node* p3 = removeByRation(pHead3, a, b);
	printList(p1);
	printList(p2);
	printList(p3);
	getchar();
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值