标签:leetcode
Reverse Linked List
Reverse a singly linked list.
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(ListNode* head) { if(head==NULL) return head; stack<ListNode*>a; while(head){ //将节点都压入栈 a.push(head); head=head->next; } ListNode* root=a.top(); //先将取一个栈顶元素 a.pop(); ListNode* p=root; while(!a.empty()){ //一步步取栈顶元素 p->next=a.top(); p=p->next; a.pop(); } p->next=NULL; //最后一个节点的next要指向空 return root; } };
/** * 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) return head; stack<ListNode*>a; while(head){ a.push(head); head=head->next; } ListNode* root=(ListNode*)malloc(sizeof(ListNode));// 分配存储空间 ListNode* p=root; while(!a.empty()){ p->next=a.top(); <span style="line-height: 26.3999996185303px; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;">// 将之后的节点插在链表后</span> p=p->next; a.pop(); } p->next=NULL; return root->next; // 链表是插在root后,所有返回root->next } };
leetcode-206-Reverse Linked List
标签:leetcode
原文地址:http://blog.csdn.net/u014705854/article/details/46597735