【链表】从尾到头打印链表(逆置链表)【剑指offer】

从尾到头打印链表

http://www.nowcoder.com/questionTerminal/d0267f7f55b3412ba93bd35cfa8e8035

思路:
     1.反转链表(依次遍历链表,将插入到新链表的头部);
     2.遍历新链表,将结果保存到vector中返回。
/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/

class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        ListNode* new_head = NULL;
        vector<int> res;
        //反转链表:链表的头插法,每次都把头节点插入到新链表中作为头,并更新新链表的头节点
        while(head != NULL)
        {
            //备份head->next
            ListNode* next = head->next;
            //更新head->next
            head->next = new_head;
            //更新new_head
            new_head = head;
            //更新head
            head = next;
        }

        while(new_head != NULL)
        {
            res.push_back(new_head->val);
            new_head = new_head -> next;
        }
        return res;

    }
};
全部评论

相关推荐

01-14 19:01
吉首大学 Java
黑皮白袜臭脚体育生:加个项目吧,一般需要两个项目一业务一轮子呢,简历统一按使用了什么技术实现了什么功能解决了什么问题或提升了什么性能指标来写
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务