LeetCode第24题,交换链表的相邻节点.java
直接交换的思想很简单,遍历一次链表,进行两两交换.node
ListNode newHead = new ListNode(0); newHead.next = head; ListNode before = newHead; ListNode first = head; ListNode second = head.next; ListNode move; while(true) { move = second.next; first.next = second.next; second.next = first; before.next = second; before = first; first = move; if(move != null && move.next != null) { second = move.next; move = move.next.next; } else break; } return newHead.next;
虽然思想简单,可是,并很差实现,有点绕,首先增长一个头节点,first,second当前要交换的两个节点,before为first的前一个节点,用来连上first,move是为了更新first与second节点的节点,进入while循环后,首先把first与second交换,接着用before连上first同时更新before,而后利用move更新first与second.git
递归交换就是每次只交换头两个节点,而后把第三个节点做为下一次递归交换的头结点继续递归交换.github
if(head != null && head.next != null) { ListNode t = head.next; head.next = swapPairs(t.next); t.next = head; return t; } return head;
要注意交换的顺序,先赋值head.next,head.next为剩下的节点,而后把t连上head.ide
新建一个链表,采用尾插法,依次插入交换的节点.
对于原链表设置两个指针a与b,令a指向首个节点,b指向第二个节点,而后对于新链表,先插入b,再插入a,最后更新a,b,使a,b都指向后继的后继,这样依次插入b与a就会获得所需的链表.优化
if(head == null || head.next == null) return head; ListNode a = head; ListNode b = head.next; ListNode newHead = new ListNode(0); ListNode t = newHead; while(a != null && b != null) { t.next = new ListNode(b.val); t = t.next; t.next = new ListNode(a.val); t = t.next; if(b.next != null) b = b.next.next; a = a.next.next; } if(a != null) t.next = new ListNode(a.val); return newHead.next;
在更新a,b时,对于a不须要判断a.next是否为空,由于a.next确定为b,确定不为空,可是对于b,当到达最后一个节点时,b.next为空,所以须要加上判断.当a,b其中一个为空后跳出循环,最后的判断a是否为空表示节点个数为奇数,此时a指向最后一个节点,直接插入a.3d
对于上面的插入法,因为ab是连在一块儿的,所以能够只使用其中一个,再优化判空与插入操做.指针
ListNode newHead = new ListNode(0); ListNode t = newHead; while(head != null) { if(head.next != null) { t.next = new ListNode(head.next.val); t = t.next; } t.next = new ListNode(head.val); t = t.next; if(head.next == null) break; head = head.next.next; } return newHead.next;
要注意while中的判空条件,由于节点的个数有多是奇数,在插入后一个节点前须要先判断是否为空,再插入前一个节点.code
githubblog