Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

Example of nodes in a pairwise exchange list

Shulou Source: shulou.com Published: 2022-06-02 10:12:45 10月02日 Update

This article mainly explains "the node example in the pairwise exchange list". The explanation in the article is simple and clear, and it is easy to learn and understand. let's study and learn the node example in the pairwise exchange list.

Solve the problem by yourself for the first time (timed out)

Public ListNode swapPairs (ListNode head) {

ListNode curr = head

While (curr! = null) {

ListNode next = curr.next.next

If (next! = null) {

ListNode temp = curr

Curr = next

Curr.next.next = temp

}

}

Return curr

}

Solve the problem for the second time (timeout error)

Public ListNode swapPairs (ListNode head) {

ListNode curr = head

ListNode pre = head.next

While (curr! = null & & pre! = null) {

ListNode a = curr

ListNode b = curr.next

/ / modify the pointer of the current node to the previous node

A.next = pre

Pre.next = b

Curr = b.next

Pre = b

}

Return pre

}

Read the answer after the analysis

Public ListNode swapPairs (ListNode head) {/ / create an empty node to point to the header pointer ListNode pre = new ListNode (0) by default; pre.next = head; / / temp points to the first node ListNode temp = pre; while (temp.next! = null & & temp.next.next! = null) {/ / the element to be exchanged ListNode a = temp.next / / the next element to be exchanged is ListNode b = temp.next.next; / / temp pointing to b temp.next = b; / a pointing to b.next a.next = b.next.b pointing to a b.next = a; / / turning the exchanged a node into the starting node temp = a;} / /? This return value still does not understand skipping return pre.next;} Thank you for your reading. The above is the content of the "example of nodes in the pairwise exchange list". After the study of this article, I believe you have a deeper understanding of the example of nodes in the pairwise exchange list, and the specific usage still needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: Nodes points examples elements learning content pointers that is ideas situations articles more knowledge knowledge points first time answers articles follow or errors Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia Shulou Tech Info OPPO Reno vpn Microsoft