码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode-206-Reverse Linked List

时间:2015-06-23 10:18:18      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:leetcode

                                       Reverse Linked List

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(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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!