首页 > 其他 > 详细

LeetCode:Reverse LinkedList

时间:2015-06-16 21:07:24      阅读:216      评论:0      收藏:0      [点我收藏+]

problem:

Reverse a singly linked list.

Hint:

A linked list can be reversed either iteratively or recursively. Could you implement both?

solution:头插法逆转链表

/**
 * 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) {
        ListNode result(-1);       
        ListNode *cur=head;
        while(cur!=NULL)
        {
            ListNode *nnode=new ListNode(cur->val);
            nnode->next=result.next;
            result.next=nnode;       
            cur=cur->next;
        }
        return result.next;
    }
};

 

LeetCode:Reverse LinkedList

原文:http://www.cnblogs.com/xiaoying1245970347/p/4581653.html

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