New Problem "Reverse Linked List "

This commit is contained in:
Hao Chen 2015-06-09 09:51:47 +08:00
parent 6836b5c7cf
commit eccaf5d590
2 changed files with 51 additions and 0 deletions

View File

@ -7,6 +7,7 @@ LeetCode
| # | Title | Solution | Difficulty |
|---| ----- | -------- | ---------- |
|190|[Reverse Linked List ](https://leetcode.com/problems/reverse-linked-list/)| [C++](./algorithms/reverseLinkedList/reverseLinkedList.cpp)|Easy|
|189|[Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/)| [C++](./algorithms/isomorphicStrings/IsomorphicStrings.cpp)|Easy|
|188|[Count Primes](https://leetcode.com/problems/count-primes/)| [C++](./algorithms/countPrimes/CountPrimes.cpp)|Easy|
|187|[Remove Linked List Elements](https://leetcode.com/problems/remove-linked-list-elements/)| [C++](./algorithms/removeLinkedListElements/RemoveLinkedListElements.cpp)|Easy|

View File

@ -0,0 +1,50 @@
// Source : https://leetcode.com/problems/reverse-linked-list/
// Author : Hao Chen
// Date : 2015-06-09
/**********************************************************************************
*
* Reverse a singly linked list.
*
* click to show more hints.
*
* Hint:
* A linked list can be reversed either iteratively or recursively. Could you implement both?
*
*
**********************************************************************************/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList_iteratively(ListNode* head) {
ListNode *h=NULL, *p=NULL;
while (head){
p = head->next;
head->next = h;
h = head;
head = p;
}
return h;
}
ListNode* reverseList_recursively(ListNode* head) {
if (head==NULL || head->next==NULL) return head;
ListNode *h = reverseList_recursively(head->next);
head->next->next = head;
head->next = NULL;
return h;
}
ListNode* reverseList(ListNode* head) {
return reverseList_iteratively(head);
return reverseList_recursively(head);
}
};