1. 程式人生 > >【資料結構】連結串列相關練習題:反轉連結串列

【資料結構】連結串列相關練習題:反轉連結串列

反轉一個單鏈表。

示例:

輸入: 1->2->3->4->5->NULL
輸出: 5->4->3->2->1->NULL

這道題有兩種思路

①傳統的使用三個指標:兩個指標用來交換,另一個指標用來向前走  ,具體程式碼如下:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* reverseList(struct ListNode* head) 
{
    if(head==NULL||head->next==NULL)
        return head;
    struct ListNode* n1,*n2,*n3;
    n1=head;
    n2=n1->next;
    n3=n2->next;
    n1->next=NULL;
    while(n2)
    {
       n2->next=n1;
        n1=n2;
        n2=n3;
        if(n3)
            n3=n3->next;
    }
    return n1;
 }

②頭插的方法,具體程式碼如下:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* reverseList(struct ListNode* head) 
{
        struct ListNode* newhead=NULL;
        struct ListNode* cur=head;
        while(cur)
        {
            struct ListNode* next=cur->next;
            cur->next=newhead;
            newhead=cur;
            cur=next;
        }
        return newhead;
 }