LeetCode 206. Reverse Linked List

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?

一,算法分析

头插法重建单链表,注意默认链表是没有头结点的,所以建表的时候不断更新head节点;Hint中的提示应该有其他更效率办法,今天就先不看了,第二遍再看吧

二,C语言实现

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* reverseList(struct ListNode* head) {//同样是不带头结点
    struct ListNode *p,*q;
    if(head==NULL || head->next==NULL)
        return head;
    p=head->next;
    head->next=NULL;
    while(p!=NULL){
        q=p->next;
        p->next=head;
        head=p;
        p=q;
    }
    return head;
}


你可能感兴趣的:(LeetCode,算法,C语言,单链表)