206 Reverse Linked List

来源:互联网 发布:vb精简版6.0怎么安装 编辑:程序博客网 时间:2024/04/24 10:28

206 Reverse Linked List

链接:https://leetcode.com/problemset/algorithms/
问题描述:
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?

这个问题是链表求逆,废话不多,直接上代码吧。
递归版:

struct ListNode* reverseList(struct ListNode* head){    if(head==NULL||head->next==NULL) return head;    struct ListNode *temp1=head;    struct ListNode *temp2;    while(temp1->next!=NULL)    {        temp2=temp1;        temp1=temp1->next;    }     temp2->next=NULL;    temp1->next=temp2;    reverseList(head);    return temp1;}

非递归版:

struct ListNode* reverseList(struct ListNode* head){    if(head==NULL||head->next==NULL) return head;    struct ListNode *temp1=NULL;    struct ListNode *temp2=NULL;    while(head!=NULL)    {      temp2=head->next;      head->next=temp1;      temp1=head;      head=temp2;    }     return temp1;}
0 0
原创粉丝点击