Algorithm and data structure: reverse linked list (overall reverse, partial reverse)

1. Problem: overall inversion of linked list

Title: reverse the whole list
For example: the chain table 1 > 2 > 3 > 4 > 5 is reversed to 5 > 4 > 3 > 2 > 1.

//Algorithm idea: record the previous node and the next node of the current traversal node to ensure that each backward traversal can be found
//The previous node of the current node completes the inversion of the linked list with the minimum time complexity of O(n)
listNode * listReverse_all(listNode * list) {
	listNode * nextNode = list->next;	
	listNode * rNode = list;
	listNode * beforeNode = NULL;

	while (nextNode != NULL) {
		rNode->next = beforeNode;
		beforeNode = rNode;
		rNode = nextNode;
		nextNode = nextNode->next;
	}

	rNode->next = beforeNode;
	
	return rNode;
}

2. Partial reversal of linked list

Title: reverse the part of the list
Input: given a linked list and a number, reverse the parts of the linked list according to the number size

If every two bits of the list 1 – > 2 – > 3 – > 4 – > 5 are reversed, the list and the number 2 are given, and some of them are reversed to get the list.
2–>1–>4–>3–>5

listNode * listReverse_part(listNode * list, int k) {

	if (k <= 1 || list == NULL) {
		return list;
	}

	listNode * cur = list;	//Point to the currently traversed node
	listNode * newHead = NULL;	//The head node of a partially reversed linked list
	listNode * sectionHead = NULL;	//Header of reverse part
	listNode * sectionTail = NULL;	//Tail of reverse part
	listNode * preTail = NULL;	//Tail of the previous part (used to connect with the next part of the header)
	int sectionNum = 0;	//Reverse records to parts


	while (cur != NULL) {
		int count = k;	//Number of records reversed
		preTail = sectionTail;
		sectionTail = cur;

		while (count-- && cur != NULL) {	
			listNode * tmp = cur;	//tmp represents the current node
			cur = cur->next;	//With tmp save, we point cur to the next node.
			tmp->next = sectionHead;	//Reverse the nodes pointed by tmp
			sectionHead = tmp;	//sectionHead is used to record the previous node of the next node to be reversed.
		}

		sectionNum++;
		if (sectionNum == 1) {
			newHead = sectionHead;
		}
		else {
			preTail->next = sectionHead;
		}
	}

	sectionTail->next = NULL;

	return newHead;
}

input

10 / / chain length    
1 2 3 4 5 6 7 8 9 10 / / number in the list
 4 / / partial flip length

output

4 3 2 1 8 7 6 5 10 9

Added by Bhaal on Thu, 24 Oct 2019 01:37:58 +0300