lintcode 35 翻转链表

来源:互联网 发布:mac pro使用教程最新 编辑:程序博客网 时间:2024/05/21 11:12

1.翻转一个链表

2.尾插法,创建dummy保存head的地址,将创建的temp保存到head->next的地址,这样就让head下移,然后指回原来的地址就可以实现链表的翻转

3.

/**
 * Definition of ListNode
 * 
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 * 
 *     ListNode(int val) {
 *         this->val = val;
 *         this->next = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param head: The first node of linked list.
     * @return: The new head of reversed linked list.
     */
    ListNode *reverse(ListNode *head) {
        // write your code here
           ListNode *dummy=NULL;
        while(head!=NULL){
            ListNode *temp=head->next;
            head->next=dummy;
            dummy=head;
            head=temp;
        }
        return dummy;
    }
};

4.感想

一开始不会做,只能百度.......看到别人写的代码,好好学习....

0 0