Data Structure - 2.7 Exercises inverted list (recursive and iterative two implementations) LeetCode (206)

  • Flip the list of issues is one of the highest frequency of appearance programmer interview, the common solution is divided into two kinds of recursive and iterative. Recently, when the review found information on the Internet only told how to do, but did not properly introduce the implementation process and the principle of the two methods. So I feel the need to properly organize a blog post, a step by step to help you understand the implementation details. 
  • We know iteration is processed sequentially from front to back, until the loop to the end of the chain; and recursion on the contrary, has been first iteration to the end of the chain is recursive Standards-based judgment, layer by layer and then return to the beginning of the process. In summary, the operation for reversing the order of the list iteration is to the head end of the chain from the chain, and for recursively from the end of the chain to the first chain. Now I will use detailed graphic to analyze the details to achieve. 

1. Non-recursive (iterative) way 

  • Iterative manner is to start the process from the first chain, as given in FIG. 5 a list of the number of storage.

  • First, the list is provided for two pointers:

  • Followed by the old list is added after each new list, and the list of the new head pointer NewH new list head is moved, as shown in FIG. It should be noted here, can not come immediately to the figure above P-> next point directly NewH, so storage address 2 will be discarded, saved list of follow-up data also will be inaccessible. But it should set up a temporary pointer tmp, temporarily point to P-> next points to the address space, preservation of the original list follow-up data. Then let P-> next point NewH, and finally P = tmp can retrieve data in the original list, all access cycle can continue to expand it.

  • Pointer continues to move rearwardly until the stop iterating P pointer to NULL.

  • last step:

  • Non-recursive program
struct ListNode* reverseList(struct ListNode* head)
{
    if (head == NULL || head->next == NULL) //链表为空或者仅1个数直接返回
        return head;
    
    struct ListNode* p,*newH;
    p=head;
    newH=NULL;
    
    while (p)                
    {
        struct ListNode* q;
        q= p->next;          
        p->next = newH;               
        newH = p;                    
        p = q;                   
    }
    
    return newH;
}

2. recursively 

  • We look at recursive list flipped to achieve, in front of non-recursive way is to start from the front of the number 1 followed by later processing, and recursively, by contrast, it first found the rearmost point of the cycle number 5, then from 5 to start processing order flip the entire list. 
  • First iteration pointer H in the end as shown below, and sets a new pointer as the head of the linked list after inversion. As the head of the entire list after the last number is reversed, so the whole process has been NewH pointer points to address storage space 5.

  • When pointer H layer by layer and then returned in order to do the processing in the figure below, assign the address pointed to H H-> next-> next pointer, and be sure to remember to make H-> next = NULL, which is now disconnected pointer link, or a ring formed new list, the next layer H-> next-> next time will be assigned to cover the subsequent value.

  • Continue to return operations:

  • The figure will be stored without first next pointer pointing to the space assignment 4 NULL, the second H-> next-> next = H, it will store the address space 5 is covered with 3, so that the list all the chaos. Then return down layer by layer, until the address space for 1 deal.

  • Return head:

  • Recursive program
struct ListNode* reverseList(struct ListNode* head)
{
    if (head == NULL || head->next == NULL)      
        return head;
    
    struct ListNode* newHead = reverseList(head->next); 
    head->next->next = head;                      
    head->next = NULL;                         
    
    return newHead;                          
}

3. First Node inverted list

  • Topic Description: / * design an algorithm to traverse through the trip, all the links in the chain direction is reversed, the original use of space still table * /
  • Thought: the first node of the first chain pointer field blanking, the first node of the linked list pointed to by p; Q * p successor point, * p will then later inserted into the head node.
void TurnList(LinkList &L) 
{
	struct LNode *p;
	p = L->next;
	L->next = NULL;
	while (p) 
	{
		LNode *q;
		q = p->next;     //   q指向*p的后继 
		p->next = L->next;
		L->next = p;    // 将*p插入到头结点之后 
		p = q;
	}
}
  • Code
  • main.cpp
#include<iostream>

using namespace std;

typedef struct LNode 
{
	int data;
	struct LNode *next;
}LNode, *LinkList;

int InitList(LinkList &L) 
{
	L = new LNode;
	L->next = NULL;
	return 1;
}

void TraveList(LinkList L)
{
	LNode *p;
	p = L->next;
	
	printf("遍历链表:\n");
	while (p) 
	{
		printf("%d ", p->data);
		p = p->next;
	}
	printf("\n");
}

//前插法创建单链表 
void CreateList(LinkList &L, int n) 
{
	L = new LNode;
	L->next = NULL;
	for (int i = n; i > 0; --i) 
	{
		printf("请输入第%d个元素的值:", i);
		struct LNode *p;
		p = new LNode;
		scanf("%d", &p->data);
		p->next = L->next;
		L->next = p;
	}
}

/*
思想:
先将链表的头结点指针域置空,p指向链表的第一个结点;
q指向*p的后继,然后将*p插入到头结点的后面。
*/
void TurnList(LinkList &L) 
{
	struct LNode *p;
	p = L->next;
	L->next = NULL;
	while (p) 
	{
		LNode *q;
		q = p->next;     //   q指向*p的后继 
		p->next = L->next;
		L->next = p;    // 将*p插入到头结点之后 
		p = q;
	}
}

int main() 
{
	LinkList L;

	if (InitList(L)) 
	{
		printf("链表初始化成功!\n");
	}
	else 
	{
		printf("链表初始化失败!\n");
	}

	printf("请输入链表的长度:\n");
	int n;
	scanf("%d", &n);
	CreateList(L, n);
	TraveList(L);

	printf("反转后的链表:\n");
	TurnList(L);
	TraveList(L);

	system("pause");

	return 0;
}
  • operation result

Guess you like

Origin blog.csdn.net/qq_22847457/article/details/93041019