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

LeetCode:Reverse LinkedList

时间:2015-06-16 21:09:03      阅读:175      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!