一方向チェーンテーブル関連アルゴリズム問題(C++)
4294 ワード
前のチェーンテーブルに基づいて、チェーンテーブルに対する管理の理解を作成します.https://www.jianshu.com/p/d1fdc35e7546)を使用して、関連アルゴリズムを拡張します.
1.2つの整列チェーンテーブルの共通部分を印刷する
2、単一チェーンテーブルの最後からk番目のノードを削除する
3、チェーンテーブルの中間ノードを削除する
4、一方向チェーンテーブルの反転
3、反転部分の一方向チェーンテーブル
1.2つの整列チェーンテーブルの共通部分を印刷する
/**
*
* @param head1
* @param head2
*
* :
* 1: head1 head2 , head1 , head2 。
* 2: head1 head2 , , head1 head2 。
* 3: null, 。
*
*/
void printCommonPart(IntSLLNode* head1, IntSLLNode* head2) {
if (head1 == 0 && head2 == 0) {
return;
}
while (head1 != 0 && head2 != 0) {
if (head1->info < head2->info) {
head1 = head1->next;
} else if (head2->info < head1->info) {
head2 = head2->next;
} else {
std::cout<info<<:endl head1="head1-">next;
head2 = head2->next;
}
}
}
2、単一チェーンテーブルの最後からk番目のノードを削除する
/**
* k
* @param head
* @param lastKth
* @return
*
* :
* 1:k>0 ,k
* 2:k == 0 , 。
* 3:k < 0 ,k - n 。
*
* : lastKth , ++, , 。
*/
IntSLLNode* removeLastKthNode(IntSLLNode* head, int lastKth) {
if (head == 0 && lastKth < 1) {
return head;
}
IntSLLNode *cur = head;
while (cur != 0) {
lastKth--;
cur = cur->next;
}
if (lastKth == 0) {
head = head->next;
}
if (lastKth < 0) {
cur = head;
while (++lastKth != 0) {
cur = cur->next;
}
cur->next= cur->next->next;
}
return head;
}
3、チェーンテーブルの中間ノードを削除する
/**
*
* @param head
* @return
*
* :
* : 2, 。
*/
IntSLLNode* removeMidNode(IntSLLNode* head) {
if (head == 0 || head->next == 0) {
return head;
}
if (head->next->next == 0) {
return head->next;
}
IntSLLNode* pre;
IntSLLNode* cur = head->next->next;
while (cur->next != 0 && cur->next->next != 0) {
pre = pre->next;
cur = cur->next->next;
}
pre->next = pre->next->next;
return head;
}
4、一方向チェーンテーブルの反転
/**
*
* @param head
* @return
* :
* , next , , next next 。
*/
IntSLLNode* reverseList(IntSLLNode* head) {
if (head == 0 || head->next == 0) {
return head;
}
IntSLLNode* newHead = 0;
IntSLLNode* node;
while (head != 0) {
node = head;
head = head->next;
node->next = newHead;
newHead = node;
}
return head = node;
}
3、反転部分の一方向チェーンテーブル
/**
*
* @param head
* @param from
* @param to
* @return
*
* :
* , , 。
*/
IntSLLNode* reverseListPart(IntSLLNode* head, int from , int to) {
if (head == 0 || head->next == 0) {
return head;
}
int hStep = 1;
IntSLLNode* originNode = head;
IntSLLNode* pre;
IntSLLNode* newHead = NULL;
while (hStep != from) {
head = head->next;
hStep++;
if (hStep == from - 1) {
pre = head;
}
}
IntSLLNode* node;
IntSLLNode* newTail;
while (hStep != (to + 1)) {
if (hStep == from) {
newTail = head;
}
node = head;
head = head->next;
node->next = newHead;
newHead = node;
hStep++;
}
if (head != 0) {
pre->next = node;
newTail->next = head;
}
return originNode;
}