Created
December 13, 2014 17:30
-
-
Save sturgle/095fab2594865ad2bf59 to your computer and use it in GitHub Desktop.
reverse a linked list with array as member
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <vector> | |
using namespace std; | |
struct ListNode { | |
vector<int> vec; | |
ListNode *next; | |
ListNode() : next(NULL) {}; | |
ListNode(int start, int end) : next(NULL) { | |
for (int i = start; i <= end; i++) { | |
vec.push_back(i); | |
} | |
} | |
}; | |
void printList(ListNode *head) { | |
ListNode *node = head; | |
while (node != NULL) { | |
cout << "("; | |
for (int i = 0; i < node->vec.size(); i++) { | |
cout << node->vec[i] << ", "; | |
} | |
cout << ") ==> "; | |
node = node->next; | |
} | |
cout << endl; | |
} | |
// build a sample list | |
ListNode *buildList() { | |
ListNode *node1 = new ListNode(1, 3); | |
ListNode *node2 = new ListNode(4, 8); | |
node1->next = node2; | |
ListNode *node3 = new ListNode(9, -1); | |
node2->next = node3; | |
ListNode *node4 = new ListNode(9, 9); | |
node3->next = node4; | |
ListNode *node5 = new ListNode(10, 12); | |
node4->next = node5; | |
return node1; | |
} | |
ListNode *reverseList(ListNode *head) { | |
ListNode *prev = NULL; | |
ListNode *temp = head; | |
while (temp != NULL) { | |
ListNode *next = temp->next; | |
temp->next = prev; | |
prev = temp; | |
temp = next; | |
} | |
return prev; | |
} | |
int main() { | |
ListNode *head = buildList(); | |
printList(head); | |
ListNode *newHead = reverseList(head); | |
printList(newHead); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment