您的位置:首页 > 其它

Reverse Linked List

2015-09-28 21:16 316 查看
【题目描述】

Reverse a singly linked list.

【思路】

新建一个链表,每从旧链表中得到一个节点就放到这个链表的最前面。

【代码】

/**
 * 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||head->next==NULL) return head;   
        ListNode* nhead=NULL;
        ListNode* current=head;
        while(current!=NULL){
            ListNode* tmp=current;
            current=current->next;
            tmp->next=nhead;
            nhead=tmp;
        }
        return nhead;
        
        
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: