Reverse Linked List I
Reverse a singly linked list.
Reverse Linked List I
设置三个指针即可,非常简单:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* reverseList(ListNode* head) { if(head==NULL || head->next == NULL){ return head; } ListNode* firstNode = head; ListNode* preCurNode = head; ListNode* curNode = head->next;//maybe null while(curNode){ preCurNode->next = curNode->next; curNode->next = firstNode; firstNode=curNode; curNode =preCurNode->next; } return firstNode; } };
Reverse Linked List II
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.
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* reverseBetween(ListNode* head, int m, int n) { if(head==NULL||head->next==NULL||m==n) return head; ListNode* firstNode = head; ListNode* preCurNode = head; ListNode* curNode = head->next;//maybe null ListNode* lastNode= head; int flag=1; int m_flag=flag; if(m==1) { while(flag<n) { preCurNode->next = curNode->next; curNode->next = firstNode; firstNode=curNode; curNode =preCurNode->next; flag++; } return firstNode; } else { while(flag<n) { if(flag<m) { lastNode=firstNode; firstNode=firstNode->next; preCurNode =preCurNode->next; curNode =curNode->next; flag++; } else { preCurNode->next = curNode->next; curNode->next = firstNode; firstNode=curNode; curNode =preCurNode->next; lastNode->next=firstNode; flag++; } } return head; } } };