Swap Nodes in Pairs
Description
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list’s nodes, only nodes itself may be changed.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
Solution
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
// 申请res结点和pre
ListNode res = new ListNode(-1), pre = res;
res.next = head;
while(pre.next != null && pre.next.next != null){
//
ListNode node = pre.next.next;
//以下三行:调序
pre.next.next = node.next;
node.next = pre.next;
pre.next = node;
pre = node.next;//指针右移
}
return res.next;//除了自己构造的头结点,后面的返回
}
}
Appendix
1.单链表中,增加一个头结点的目的是为了 。方便运算的实现
2.讲解过程来自牛客网
3.通过这个题目熟悉链表的操作以及原理