Niuke Classic Linked List Question—(NC78) Reverse Linked List

Full difficulty factor * * * * *, the difficulty factor of this question * *.
Frequent enthusiasm for full exams, enthusiasm * * * * *for this question * * * * *.

1. Title description

Insert picture description here

2. Topic link

  1. Reverse link list

3. Problem analysis

  1. Reverse the given linked list and output the head of the new linked list.
  2. The time complexity is O(n). Traverse one side of the linked list from the beginning without repeating the loop traversal.
  3. The space complexity is O(1). Do not open up new linked list nodes. Realize in situ.

3.1 Analysis icon

Insert picture description here

3.2 Detailed explanation of icons

  1. Node is initially empty, so that next after head(cur) is reversed points to empty.
  2. cur is initially head.
  3. Next is the next of cur, and the Next node comes first every time to 记录cur的nextensure the continuation of the iteration.

Iterative core code: (process as shown above)

		Node = Cur;
        Cur = Next;
        Next = Cur->next;
        Cur -> next = Node;

4. Problem-solving code

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 */

/**
 1. 
 2. @param pHead ListNode类 
 3. @return ListNode类
 */
typedef struct ListNode ListNode;
struct ListNode* ReverseList(struct ListNode* pHead ) {
    
    
    if(pHead == NULL) //注释1
    {
    
    
        return NULL;
    }
    
    //注释二
    ListNode* Node = NULL;
    ListNode* Cur = pHead;
    ListNode* Next = Cur->next;
    
    Cur->next = Node;
	
	//注释3
    while(Next)
    {
    
    
        Node = Cur;
        Cur = Next;
        Next = Cur->next;
        Cur -> next = Node;
    }
    
    return Cur;
}

5. Detailed explanation of code comments

  1. Note 1: The head pointer is nullified first. So as not Next = Cur->nextto cause null pointer access from time to time.
  2. Note 2: First process the head of the iteration. Of each node 初始相对位置进行归位.
  3. Note 3: To achieve iteration, the process is as shown in the figure above. When Next为空时,链表访问完毕. The new head node is cur, and the new head node after the inversion is returned.

1.如有错误或者没能理解的地方,请及时评论或者私信,及时修改更新
2.会持续更新相关链表高频题目,分类专栏—数据结构

Guess you like

Origin blog.csdn.net/weixin_45313447/article/details/115249141