Leetcode: 25. Reverse Nodes in k-Group

来源:http://www.cnblogs.com/lengender-12/archive/2017/05/08/6823620.html
-Advertisement-
Play Games

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. k is a positive integer and is less than or equal t... ...


Description

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

You may not alter the values in the nodes, only nodes itself may be changed.

Only constant memory is allowed.

Example

For example,
Given this linked list: 1->2->3->4->5

For k = 2, you should return: 2->1->4->3->5

For k = 3, you should return: 3->2->1->4->5

思路

  • k-group反轉
  • 首先寫一個單鏈表反轉函數,指定頭結點和尾節點,然後再函數中反轉鏈表
  • 從給定鏈表頭開始,每次讀取k個長度的鏈表,調用反轉函數,然後再繼續這個過程
  • 註意考慮兩個反轉鏈表之間的連接時候的情況
  • 代碼

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
        if(k == 1) return head;
        
        ListNode *res = NULL, *ptr = NULL, *cur = NULL, *pre = NULL;
        while(head){
            int count = k;
            ptr = NULL;
            cur = head;
            //while實現每次截取k個長度的鏈表
            while(head){
                if(ptr == NULL)
                    ptr = head;
                    
                cur = head;
                head = head->next;
                count--;
                if(count == 0) break;
            }
            
            //此時需要反轉
            if(count == 0 && cur && ptr){
                Reverse(&ptr, &cur);
            } 
            
            //連接兩個反轉部分或不反轉部分
            if(!pre){
                pre = cur;
            }
            else{
                pre->next = ptr;
                pre = cur;
            }
         
            //記錄反轉鏈表的頭節點
            if(!res) res = ptr;
            
            //特殊情況考慮,即剛好反轉到鏈表末尾
            if(!head && count == 0) pre->next = NULL;
        }
        
        return res;
    }
    
    //反轉單鏈表
    void Reverse(ListNode **head, ListNode **tail){
        ListNode *end = *tail, *cur = *head, *ptr = NULL, *tmp = NULL;
       
        ptr = cur->next; 
        *tail = cur;
        while(ptr != end){
            tmp = ptr->next;
            ptr->next = cur;
            cur = ptr;
            ptr = tmp;
        }
        
        if(ptr != end)
            end->next = ptr;
        else
            end->next = cur;
           
        *head = end;
    }
};

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • shop_list=[]shop_cart=[]product_list=open("test.txt",'a+') #讀取文件中的商品product_list.seek(0,0)for line in product_list.readlines(): (product,price)=line.s ...
  • PHP trim()函數一般是用來去除字元串首尾處的空白字元(或者其他字元),一般在用在服務端對接收的用戶數據進行處理,以免把用戶誤輸入的空格存儲到資料庫,下次對比數據時候出錯。 該函數有兩個參數,第二個可以為空,格式如下: trim ( string $str [, string $charact ...
  • 1)流序列化對象ObjectOutputStream調用writerObject寫出序列化對象,ObjectInputStream調用readObject讀取序列化對象,序列化的對象必須要實現Serializable介面,該介面沒有任何需要待實現的方法,只需繼承即可。序列化之前的對象和序列化之後的對 ...
  • linux 2cpu 16g記憶體 ,tomcat7 JAVA_OPTS="-Xmx1024m -Xms1024m -Xss1024K -XX:PermSize=512m -XX:MaxPermSize=1024m"cygwin=false 堆記憶體: xmx,xms最大為物理記憶體的1/4,同樣大小,省 ...
  • 首先,安裝一下STS阿裡雲的jar包,官方文檔詳情在https://help.aliyun.com/document_detail/28788.html?spm=5176.doc28789.6.704.dasE9X,jar包地址https://docs-aliyun.cn-hangzhou.oss. ...
  • Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. ...
  • 看了好多關於代理的文章,理解和整理一下。 1、代理的基本構成 抽象角色:聲明真實對象和代理對象的共同介面,這樣可在任何使用真實對象的地方都可以使用代理對象。 代理角色:代理對象內部含有真實對象的引用,從而可以在任何時候操作真實對象。代理對象提供一個與真實對象相同的介面,以便可以在任何時候替代真實對象 ...
  • Description Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. Do not allocate ex ...
一周排行
    -Advertisement-
    Play Games
  • 前言 本文介紹一款使用 C# 與 WPF 開發的音頻播放器,其界面簡潔大方,操作體驗流暢。該播放器支持多種音頻格式(如 MP4、WMA、OGG、FLAC 等),並具備標記、實時歌詞顯示等功能。 另外,還支持換膚及多語言(中英文)切換。核心音頻處理採用 FFmpeg 組件,獲得了廣泛認可,目前 Git ...
  • OAuth2.0授權驗證-gitee授權碼模式 本文主要介紹如何筆者自己是如何使用gitee提供的OAuth2.0協議完成授權驗證並登錄到自己的系統,完整模式如圖 1、創建應用 打開gitee個人中心->第三方應用->創建應用 創建應用後在我的應用界面,查看已創建應用的Client ID和Clien ...
  • 解決了這個問題:《winForm下,fastReport.net 從.net framework 升級到.net5遇到的錯誤“Operation is not supported on this platform.”》 本文內容轉載自:https://www.fcnsoft.com/Home/Sho ...
  • 國內文章 WPF 從裸 Win 32 的 WM_Pointer 消息獲取觸摸點繪製筆跡 https://www.cnblogs.com/lindexi/p/18390983 本文將告訴大家如何在 WPF 裡面,接收裸 Win 32 的 WM_Pointer 消息,從消息裡面獲取觸摸點信息,使用觸摸點 ...
  • 前言 給大家推薦一個專為新零售快消行業打造了一套高效的進銷存管理系統。 系統不僅具備強大的庫存管理功能,還集成了高性能的輕量級 POS 解決方案,確保頁面載入速度極快,提供良好的用戶體驗。 項目介紹 Dorisoy.POS 是一款基於 .NET 7 和 Angular 4 開發的新零售快消進銷存管理 ...
  • ABP CLI常用的代碼分享 一、確保環境配置正確 安裝.NET CLI: ABP CLI是基於.NET Core或.NET 5/6/7等更高版本構建的,因此首先需要在你的開發環境中安裝.NET CLI。這可以通過訪問Microsoft官網下載並安裝相應版本的.NET SDK來實現。 安裝ABP ...
  • 問題 問題是這樣的:第三方的webapi,需要先調用登陸介面獲取Cookie,訪問其它介面時攜帶Cookie信息。 但使用HttpClient類調用登陸介面,返回的Headers中沒有找到Cookie信息。 分析 首先,使用Postman測試該登陸介面,正常返回Cookie信息,說明是HttpCli ...
  • 國內文章 關於.NET在中國為什麼工資低的分析 https://www.cnblogs.com/thinkingmore/p/18406244 .NET在中國開發者的薪資偏低,主要因市場需求、技術棧選擇和企業文化等因素所致。歷史上,.NET曾因微軟的閉源策略發展受限,儘管後來推出了跨平臺的.NET ...
  • 在WPF開發應用中,動畫不僅可以引起用戶的註意與興趣,而且還使軟體更加便於使用。前面幾篇文章講解了畫筆(Brush),形狀(Shape),幾何圖形(Geometry),變換(Transform)等相關內容,今天繼續講解動畫相關內容和知識點,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 什麼是委托? 委托可以說是把一個方法代入另一個方法執行,相當於指向函數的指針;事件就相當於保存委托的數組; 1.實例化委托的方式: 方式1:通過new創建實例: public delegate void ShowDelegate(); 或者 public delegate string ShowDe ...