Reverse Linked List

来源:互联网 发布:飞机大战游戏设计java 编辑:程序博客网 时间:2024/06/18 07:27

Reverse Linked List

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* cur = head->next;        head->next = NULL;        while(cur!=NULL)        {            ListNode* tmp = cur->next;            cur->next = head;            head = cur;            cur = tmp;        }        return head;    }};


代码递归

这里写图片描述

0 0
原创粉丝点击