Reverse linked list
Full difficulty factor
* * * * *
, the difficulty factor of this question* *
.
Frequent enthusiasm for full exams, enthusiasm* * * * *
for this question* * * * *
.
1. Title description
2. Topic link
3. Problem analysis
- Reverse the given linked list and output the head of the new linked list.
- The time complexity is O(n). Traverse one side of the linked list from the beginning without repeating the loop traversal.
- The space complexity is O(1). Do not open up new linked list nodes. Realize in situ.
3.1 Analysis icon
3.2 Detailed explanation of icons
- Node is initially empty, so that next after head(cur) is reversed points to empty.
- cur is initially head.
- Next is the next of cur, and the Next node comes first every time to
记录cur的next
ensure 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
- Note 1: The head pointer is nullified first. So as not
Next = Cur->next
to cause null pointer access from time to time. - Note 2: First process the head of the iteration. Of each node
初始相对位置进行归位
. - 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.会持续更新相关链表高频题目,分类专栏—数据结构
。