数据结构3:反转链表

    科技2022-07-13  135

    题目描述

    解答

    使用倒插法,先把2插在1前,再往后走。p起到传递pre的作用。题目本身不难,但要注意涉及到同时出现head,pre,p三个指针,要判断初始它们不能创建的情况,即链表只有一项或者两项的时候。

    /** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* reverseList(struct ListNode* head){ if(!head) return false; struct ListNode *pre=head;struct ListNode *p=head; if(!head->next) return head;//链表只有一项 pre=head->next; head->next=NULL; if(!pre->next)//链表只有两项 { pre->next=head; head=pre; return head; } while(pre&&head&&p)//链表有三项及以上 { p=pre->next; pre->next=head; head=pre; pre=p; p=p->next; } pre->next=head; head=pre; return head; }
    Processed: 0.011, SQL: 8