首页 > 其他 > 详细

leetcode-206-Reverse Linked List

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

                                       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

原文:http://blog.csdn.net/u014705854/article/details/46597735

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!