程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> 以k個元素為一組反轉單鏈表,一組反轉單鏈

以k個元素為一組反轉單鏈表,一組反轉單鏈

編輯:關於C語言

以k個元素為一組反轉單鏈表,一組反轉單鏈


Example:
  input: 1->2->3->4->5->6->7->8->NULL and k = 3
  output:3->2->1->6->5->4->7->8->NULL

 

Node* inverstList(Node *head, int num)
{
    Node *prev, *curr, *next;
    int count = 0;

    if (num == 0 || num == 1)
        return head;

    prev = head;
    curr = prev->next;
    next = curr->next;

    while (num-1 > count)
    {
        if (curr != NULL)
        {
            next = curr->next;
            curr->next = prev;
            prev = curr;
            curr = next;

            count++;
        }
        else
        {
            curr = prev->next;
            prev->next = NULL;
            while (count > 0)
            {
                next = curr->next;
                curr->next = prev;
                prev = curr;
                curr = next;

                count--;
            }
            return prev;
        }    
    }

    if (next != NULL)
        head->next = inverstList(next, num);
    else
        head->next = NULL;

    return prev;
}

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved