刪除連結串列的中間節點和a/b處的節點
阿新 • • 發佈:2018-11-20
題目
給定連結串列的頭節點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;
}