Twenty-two exchange list node

Twenty-two switching node in the linked list

LeetCode

Given a list pairwise exchange with adjacent nodes, and return the list to the exchange, not simply changing the value of the internal node, but requires a node actual exchange.

Thinking

First understand the structural characteristics and the list of principle, the list is a linear table structure, data insertion and deletion low complexity, but to traverse to find high complexity. Needed to get the head of the list, which is derived from the principle of the list, we list of operation, it is a list exposure head node, to be directly or indirectly, the operation list node.

Code

Using the code implemented in Java.

class Solution {
    public ListNode swapPairs(ListNode head) {
    //定义新的链表为dummy,头结点的值0
        ListNode dummy = new ListNode(0);
   //dummy的后一个节点指向head     
       dummy.next = head;
       ListNode p = dummy;
       if(p.next == null || p.next.next == null) return head;
            //交换两个节点,修改他的next指向
           while(p.next != null && p.next.next != null){
               ListNode n1 = p.next;
               ListNode n2 = p.next.next;
               n1.next = n2.next;
               n2.next = n1;
             
}
            //重新定head
            p = n2;
        }
        //返回一个头结点,也是直接返回交换后的链表。
        ListNode result = dummy.next;
        
        return result;
    }
}

Guess you like

Origin blog.csdn.net/qq_21306815/article/details/93765238