zoukankan      html  css  js  c++  java
  • [LeetCode]Swap Nodes in Pairs

    版权声明:本文为博主原创文章。未经博主同意不得转载。 https://blog.csdn.net/yeweiouyang/article/details/37532101

    题目:给定一个单链表,要求对链表每两两节点进行交换,样例: 1->2->3->4, 交换后 2->1->4->3.

    算法:链表操作,设置4个指针

    pre:左边界,维护交换后链表的结构

    swapA:指向要交换的第一个节点

    swapB:指向要交换的第二个节点

    post:右边界,维护交换后链表的结构


    链表:...->1->2->3->4

    相应:pre  swapA  swapB  post

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
     */
    public class Solution {
        public ListNode swapPairs(ListNode head) {
    	        if (null == head) {
    	        	return null;
    	        }
    	    	
    	    	ListNode pre = head;
    	        ListNode post = null;
    	        ListNode swapA = head;
    	        ListNode swapB = null;
    	        while (null != pre) {
    	        	if (head == pre) {
    	        		// begin with the list head
    	        		if (null != pre.next) {
    	        			swapA = pre;
    	        			swapB = swapA.next;
    	        			post = swapB.next;
    	        			
    	        			// swap node pair
    	        			swapA.next = post;
    	        			swapB.next = swapA;
    	        			head = swapB;
    	        		} else {
    	        			break;
    	        		}
    	        	} else {
    //	        		pre = swapA;  // after swap
    	        		if (null != pre.next) {
    		        		swapA = pre.next;
    		        		if (null != swapA.next) {
    		        			swapB = swapA.next;
    		        			post = swapB.next;
    		        			
    		        			// swap node pair
    		        			pre.next = swapB;
    		            		swapB.next = swapA;
    		            		swapA.next = post;
    		        		} else {
    		        			break;  // last one node, don't swap
    		        		}
    		        	} else {
    		        		break;  // end of the list
    		        	}
    	        	}
    	        	
    	        	pre = swapA;  // after swap
    	        }
    	        
    	        return head;
    	    }
    }


查看全文
  • 相关阅读:
    在springmvc框架中,通过ajax请求,响应至前端的中文显示是?
    在idea中相同的字符串使用equals()进行比较时,返回值是flase问题
    Mybatis入门配置及第一个Mybatis程序
    hibernate入门配置及第一个hibernate程序
    Java中各种对象(PO,BO,VO,DTO,POJO,DAO,Entity,JavaBean,JavaBeans)的区分
    如何让iframe框架和主页面共用一个滚动条(也称为:iframe高度自适应问题)
    使用iframe框架时,实现子页面内跳转到整个页面,而不是在子页面内跳转
    第八篇 .NET高级技术之字符串暂存池(缓冲池)
    第七篇 .NET高级技术之关于相等 Equals
    第六篇 .NET高级技术之拆箱装箱
  • 原文地址:https://www.cnblogs.com/ldxsuanfa/p/10686130.html
  • Copyright © 2011-2022 走看看