当前位置:网站首页>Reverse one-way linked list of interview questions

Reverse one-way linked list of interview questions

2022-07-05 05:08:00 ximen502_

titled : Reverse a one-way linked list , Write algorithm steps or code .
Muddled . Today's learning is as follows ,
Article code reference https://blog.csdn.net/K346K346/article/details/93371829, thank !
 Schematic diagram of one-way linked list inversion

#include<iostream>
using namespace std;

typedef struct linknode {
    
	int value;
	linknode * next;
} LinkNode;

/* Loop traversal realizes the inversion of one-way linked list */
LinkNode * Reverse(LinkNode* head) {
    
	if (head == NULL || head->next == NULL) {
    
		return head;
	}

	LinkNode* pre = head, *cur = head->next;
	head->next = NULL;
	while (cur != NULL) {
    
		auto next = cur->next;
		cur->next = pre;
		pre = cur;
		cur = next;
	}
	return pre;
}

void printLink(LinkNode* head) {
    
	while (head != NULL) {
    
		cout << head->value;
		head = head->next;
		if (head != NULL) {
    
			cout << "->";
		}
	}
	cout << endl;
}

/* Recursive implementation of one-way linked list inversion */
LinkNode* Reverse2(LinkNode* head) {
    
	// Recursive termination condition 
	if (head == NULL || head->next == NULL) {
    
		return head;
	}
	LinkNode* newHead = Reverse2(head->next);
	head->next->next = head;
	head->next = NULL;
	return newHead;
}

int main(int argc, char* argv[]) {
    
	LinkNode* head = NULL, *cur = NULL;
	for (int i = 1; i <= 5; i++) {
    
		LinkNode* node = new LinkNode;
		node->value = i;
		node->next = NULL;

		if (head == NULL) {
    
			head = node;
			cur = head;
		} else {
    
			cur->next = node;
			cur = node;
		}
	}

	printLink(head);
	// Reverse one-way list 
	auto newHead = Reverse(head);
	printLink(newHead);
}

In fact, it can be summed up as
1. preservation cur Of next
2. modify cur Of next Point to pre
3. Move pre,cur The pointer :pre Point to cur,cur Point to previously saved next
loop 1,2,3 until cur by NULL end , Now pre It points to the inverted head, complete .
In fact, the data is still stored in the original place , It's just that the arrow points backwards .

About code compilation and execution , Feeling C++ Changed a lot , Structures can also be used new keyword , stay Linux above .

g++ -std=c++11 reverselink.cpp
./a.out
1->2->3->4->5
5->4->3->2->1
原网站

版权声明
本文为[ximen502_]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140623325941.html