LeetCode刷题day024 (Jieky)

LeetCode第24题

class ListNode{
     
	int val;
	ListNode next;
	ListNode(){
     };
	ListNode(int val){
     this.val=val;}
	ListNode(int val, ListNode next) {
      this.val = val; this.next = next; }
}

public class SwapNodesPairs{
     
	public static void main(String[] args){
     
		ListNode node1_1 = new ListNode(1);
		ListNode node1_2 = new ListNode(2);
		ListNode node1_3 = new ListNode(3);
		ListNode node1_4 = new ListNode(4);
		node1_1.next = node1_2;
		node1_2.next = node1_3;
		node1_3.next = node1_4;
		
		SwapNodesPairs snp = new SwapNodesPairs();
		ListNode result = snp.swapPairs(node1_1);
		
		while(result != null){
     
			System.out.println(result.val);
			result = result.next;
		}
	}
	
	// 理解不透
	public ListNode swapPairs(ListNode head) 01{
     
		if (head == null || head.next == null) return head;
		ListNode n = head.next;
		head.next = swapPairs(head.next.next);
		n.next = head;
		return n;
	}
	
	public ListNode swapPairs01(ListNode head) {
     
		if (head == null || head.next == null) return head;
		
		ListNode ret = new ListNode(-1);
		
		ListNode pre = head;
		ListNode cur = head.next;
		
		ret.next = head.next;
		pre.next = head.next.next;
		cur.next = pre;
		head = pre.next;
		
		// 剩余的节点少于2个,则跳出循环
		while(head != null && head.next != null){
     
			// temp指向两个交换节点前的节点
			ListNode temp = pre;
			// 指向待交换的第一个节点
			pre = head;
			// 指向待交换的第二个节点
			cur = head.next;
			
			// 每一次交换都有三个节点的指向发生变化
			temp.next = head.next;
			pre.next = head.next.next;
			cur.next = pre;
			
			// head指向剩余节点的表头,为下一次交换做准备
			head = pre.next;
		}
		return ret.next;
	}
}

你可能感兴趣的:(LeetCode,java,leetcode)