File tree Expand file tree Collapse file tree 2 files changed +51
-0
lines changed
algorithms/reverseLinkedList Expand file tree Collapse file tree 2 files changed +51
-0
lines changed Original file line number Diff line number Diff line change 77
88| # | Title | Solution | Difficulty |
99| ---| ----- | -------- | ---------- |
10+ | 190| [ Reverse Linked List ] ( https://leetcode.com/problems/reverse-linked-list/ ) | [ C++] ( ./algorithms/reverseLinkedList/reverseLinkedList.cpp ) | Easy|
1011| 189| [ Isomorphic Strings] ( https://leetcode.com/problems/isomorphic-strings/ ) | [ C++] ( ./algorithms/isomorphicStrings/IsomorphicStrings.cpp ) | Easy|
1112| 188| [ Count Primes] ( https://leetcode.com/problems/count-primes/ ) | [ C++] ( ./algorithms/countPrimes/CountPrimes.cpp ) | Easy|
1213| 187| [ Remove Linked List Elements] ( https://leetcode.com/problems/remove-linked-list-elements/ ) | [ C++] ( ./algorithms/removeLinkedListElements/RemoveLinkedListElements.cpp ) | Easy|
Original file line number Diff line number Diff line change 1+ // Source : https://leetcode.com/problems/reverse-linked-list/
2+ // Author : Hao Chen
3+ // Date : 2015-06-09
4+
5+ /* *********************************************************************************
6+ *
7+ * Reverse a singly linked list.
8+ *
9+ * click to show more hints.
10+ *
11+ * Hint:
12+ * A linked list can be reversed either iteratively or recursively. Could you implement both?
13+ *
14+ *
15+ **********************************************************************************/
16+
17+
18+ /* *
19+ * Definition for singly-linked list.
20+ * struct ListNode {
21+ * int val;
22+ * ListNode *next;
23+ * ListNode(int x) : val(x), next(NULL) {}
24+ * };
25+ */
26+ class Solution {
27+ public:
28+ ListNode* reverseList_iteratively (ListNode* head) {
29+ ListNode *h=NULL , *p=NULL ;
30+ while (head){
31+ p = head->next ;
32+ head->next = h;
33+ h = head;
34+ head = p;
35+ }
36+ return h;
37+ }
38+ ListNode* reverseList_recursively (ListNode* head) {
39+ if (head==NULL || head->next ==NULL ) return head;
40+ ListNode *h = reverseList_recursively (head->next );
41+ head->next ->next = head;
42+ head->next = NULL ;
43+ return h;
44+
45+ }
46+ ListNode* reverseList (ListNode* head) {
47+ return reverseList_iteratively (head);
48+ return reverseList_recursively (head);
49+ }
50+ };
You can’t perform that action at this time.
0 commit comments