This blog will be leetcode on the linklist topic content here, followed by slowly add
One: Leetcode 206 Reverse Linked list two: Leetcode Reverse Linked List II
A: Leetcode 206 Reverse Linked List
Topic:
Reverse a singly linked list.
Code:
Class Solution {public: listnode* reverselist (listnode* head) { if (head = = NULL) return null; ListNode *p = head; ListNode *pnext = p->next; P->next = NULL; The head node needs to point to NULL otherwise time limit while (pnext! = NULL) { ListNode *q = pnext->next; Pnext->next = p; p = pnext; Iteration pnext = q; } return p; }};
II: Leetcode Reverse Linked List II
Topic:
Reverse a linked list from position m to N. Do it in-place and in One-pass.
For example:
Given 1->2->3->4->5->NULL
, m = 2 and n = 4,
Return 1->4->3->2->5->NULL
.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤length of list.
Analysis: This problem is slightly more complicated than a little, but it is also easy to solve
Code:
Class Solution {public: listnode* Reversebetween (listnode* head, int m, int n) { if (m = = N) return head; ListNode *pre = head; ListNode *p = head; for (int i = 1; i < m; i++) { //Find the first M element and its previous element pre = p; p = p->next; } ListNode *curr = p; ListNode *pnext = p->next; Invert the elements that need to be reverse in the middle to take advantage of the idea in reverse linked list for (int i = m; i < n; i++) { ListNode *q = pnext->next;< C14/>pnext->next = p; p = pnext; Pnext = q; } Curr->next = Pnext; if (pre! = curr) Pre->next = p; Inequality indicates m!=1 then Pre->next = p, and equality indicates m==1, then head ==p else head = p; return head; };
Leetcode linklist Special Topic