交换链表相邻节点

题目描述:相邻节点之间互相交换位置


节点初始化:

public class ListNode {
	public int val;
	public ListNode next;

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

	public ListNode(int val) {
		super();
		this.val = val;
	}

	public static ListNode arrayToList(int[] arr) {
		ListNode head = new ListNode(0);
		ListNode p = head;
		for(int value : arr){
			p.next = new ListNode(value);
			p = p.next;
		}
		return head.next;
	}
	
	public static void printList(ListNode head){
		ListNode p = head;
		while(p != null){
			System.out.print(p.val + " ");
			p = p.next;
		}
		System.out.println();
	}
}
交换节点:

public class 交换链表相邻节点 {
	public static void main(String[] args) {
		int[] array = { 1, 2, 3, 4, 5, 6, 7, 8 , 9};
		ListNode head = ListNode.arrayToList(array);
		ListNode.printList(head);
		ListNode.printList(swapPairs(head));
	}

	/**
	 * 需要指针对应图中所示
	 * @param head
	 * @return
	 */
	private static ListNode swapPairs(ListNode head) {
		ListNode pre = head;
		ListNode p = head.next;
		ListNode next = null;
		ListNode newHead = new ListNode(0);
		newHead.next = head;
		ListNode zero = newHead;
		while (pre != null && p != null) {
			next = p.next;
			p.next = pre;
			pre.next = next;
			zero.next = p;
			if (next == null) {
				break;
			} else {
				zero = pre;
				pre = next;
				p = pre.next;
			}
		}
		return newHead.next;
	}
}

猜你喜欢

转载自blog.csdn.net/cpcpcp123/article/details/72676551