LeetCodeOJ_206_Reverse Linked List

来源:互联网 发布:java运行class文件原理 编辑:程序博客网 时间:2024/06/03 14:36

答题链接

题目:

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

代码:

/** * 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) {        //note:头为空        if( head == NULL )            return head;        ListNode* tail = head;        ListNode* temp;        while( tail->next != NULL )        {            temp = head;            head = tail->next;            tail->next = head->next;            head->next = temp;        }        return head;    }};

总结:

1、notes:(1)注意链表为空的情况

结果:

结果1

0 0
原创粉丝点击