zoukankan      html  css  js  c++  java
  • 24. Swap Nodes in Pairs

    24. Swap Nodes in Pairs

    题目

     Given a linked list, swap every two adjacent nodes and return its head.
    
    For example,
    Given 1->2->3->4, you should return the list as 2->1->4->3.
    
    Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed. 
    

    解析

    
    class Solution_24 {
    public:
    	/*两个指针分别指向奇数和偶数位置,一个指针指向前一次的结尾处先调换位置,再将其挂到上一次结尾处之后继续调整三个指针位置即可
    	*/
    	ListNode* swapPairs(ListNode* head) {
    		if (head == NULL || head->next == NULL)
    		{
    			return head;
    		}
    		ListNode* newHead = NULL;
    		ListNode* pre = NULL, *cur = head;
    		ListNode* next = NULL;
    		ListNode* temp=NULL;
    		while (cur&&cur->next)
    		{
    			pre = cur;
    			cur = cur->next;
    			next = cur->next;
    
    			pre->next = next;
    			cur->next = pre;
    			if (temp)
    			{
    				temp->next = cur; //当前挂载上一次的结尾指针上
    			}	
    			if (!newHead)
    			{
    				newHead = cur;
    			}
    			temp = pre; ///记录上一次的结尾指针
    			cur = next;
    		}
    
    		return newHead;
    	}
    };
    
    主要的思想是递归,拆分成2部分:
    
    1,将第3个节点开始的链表作为下一次递归的参数,用它去继续交换。
    2,将第1个节点指向递归返回的结果,将第2个节点重新指向第1个节点,并返回它,这是新的head。
    
    递归终止的两种情况:
    
    1,没有节点了,返回NULL作为结束。
    2,只有一个节点了,不用交换,直接返回它即可。
    
    class Solution {
    public:
        ListNode* swapPairs(ListNode* head) {
            if(head == NULL) return NULL;
            if(head->next == NULL) return head;
    
            ListNode* temp = head->next;
            head->next = swapPairs(temp->next);
            temp->next = head;
    
            return temp;
        }
    };
    

    题目来源

  • 相关阅读:
    IsDefined的问题
    设计匠艺模型
    真实案例引起的对系统健壮性的思考
    软件系统的稳定性
    LA工作第二周体会
    LA工作第一周体会
    https://blog.csdn.net/qq_26264237/article/details/90575165
    Maven项目配置logback
    Java 工具 Hutool4.0.0 正式发布:从懵懂到成熟
    IDEAidea中解决Java程序包不存在问题
  • 原文地址:https://www.cnblogs.com/ranjiewen/p/8337625.html
Copyright © 2011-2022 走看看