LeetCode:Reverse Linked List

来源:互联网 发布:c语言角度转弧度 编辑:程序博客网 时间:2024/05/18 15:27

Reverse Linked List

Total Accepted: 60024 Total Submissions: 168196 Difficulty: Easy

Reverse a singly linked list.

click to show more hints.

Hint:

A linked list can be reversed either iteratively or recursively. Could you implement both?














思路:头插法。

code:

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


0 0
原创粉丝点击