题目
给定链表的头节点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;
}