leetcode 两两交换链表中的节点 java
两种方法:递归法和迭代法。
我首先想到的是迭代,因为我不会用递归。
如果觉得很绕的话,直接把节点都定义出来。
class Solution {public ListNode swapPairs(ListNode head) {ListNode dummy = new ListNode(0,head);ListNode cur = dummy;// while(cur.next.next!=null){while(cur.next!=null && cur.next.next!=null ){// ListNode temp = cur.next;// cur.next=cur.next.next;// cur.next.next=temp;// temp.next=cur.next.next.next;// cur=cur.next.next;ListNode temp1 = cur.next;ListNode temp2 = cur.next.next;cur.next=temp2;temp1.next=temp2.next;temp2.next=temp1;cur=temp1; }return dummy.next;}
}
递归法:参考了Leetcode评论区大神的方法,很直白!
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val = val; }* ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*/
class Solution {public ListNode swapPairs(ListNode head) {//递归if(head == null || head.next==null){return head;}ListNode one = head;ListNode two = head.next;ListNode three = head.next.next;//one.next=three;two.next=one;one.next=swapPairs(three);return two;}
}