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;
        }
    };
    

    题目来源

  • 相关阅读:
    利用vector声明二维数组及获取行数和列数
    链表翻转
    关于一段测试代码的知识点补习
    初探二叉搜索树
    排序系列之——再叙堆排序
    Top k 问题
    哈希表及其冲突与排解
    进程互斥与同步
    基础算法之几种排序算法
    进程的描述、状态及控制
  • 原文地址:https://www.cnblogs.com/ranjiewen/p/8337625.html
Copyright © 2011-2022 走看看