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

leetcode 206 头插法

时间:2016-08-04 14:40:17      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:

头插法,定义temp,Node

temp指向每次头结点,Node每次指向要进行头插的节点。

最后返回temp

/**
 * 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;
        ListNode * Node,*temp;
        temp=head;//当前头结点为head
        Node=head->next;//当前要插入的是head->next
        while(Node!=NULL) {
            head->next=Node->next;//先将要插入的节点去掉
            Node->next=temp;//插入
            temp=Node;//更新头结点
            Node=head->next;//更新要插入的节点
        }
        return temp;
    }
};

 

leetcode 206 头插法

标签:

原文地址:http://www.cnblogs.com/thefirstfeeling/p/5736381.html

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