leetcode24:Swap Nodes in Pairs

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Somnus_k/article/details/82622187

思路:关于链表的题,主要将指针关系理清,在指针改变之前,需要将指针的后继节点保存,防止链表断开。

代码:

public class SwapNodesinPairs24 {

	public static void main(String[] args) {
		ListNode node1 = new ListNode(1);
		ListNode node2 = new ListNode(2);
		ListNode node3 = new ListNode(3);
		ListNode node4 = new ListNode(4);
		ListNode node5 = new ListNode(5);
		node1.next = node2;
		node2.next = node3;
		node3.next = node4;
		node4.next = node5;
		node5.next = null;
		ListNode h = new SwapNodesinPairs24().swapPairs(node1);
		while(h!=null){
			System.out.print(h.val+" ");
			h=h.next;
		}
	}

	public ListNode swapPairs(ListNode head) {
		if(head==null||head.next==null)
			return head;
		ListNode h = new ListNode(-1);
		ListNode tmp = h;
		ListNode p = head;
		ListNode q = head;
		ListNode t = head;
		
		while(p!=null){
			
			q=p.next;
			if(q==null)
				break;
			t=q.next;
			tmp.next=q;
			tmp=p;
			q.next=p;
			p.next=t;
			p=t;
		}
		return h.next;
	}
}

输出:

猜你喜欢

转载自blog.csdn.net/Somnus_k/article/details/82622187