JAVA算法问题,在一个List里,成对换位

JAVA算法问题,在一个List里,成对换位
给出一个包含node对象的list,
public class Node{
public int n; // node的值
public Node next; //list中的下一个Node,可看做指针
}
要求一个算法,更换两个Node的值和指针(Node的Node属性),在一个队列中每两个更换一次。
例如1à2à3à4à5à6… 换位成2à1à4à3à6à5…
注意:有的队列的最后一个元素的指针指向第一个元素。即node(n).nextNode==node(1)
求算法
英文版原题:
Swap pairs of elements in list
You are given a singly linked list:
struct node
{
int n; //value of element
struct node *next; //pointer to next element in list
}
Write a function that will swap pairs of elements in a given singly-linked list. Note that you have to actually swap the elements, not just the values, and that you should modify the list in place (i.e. you should not create a copy of the list).
struct node *swapPairs(struct node *l);
For instance, the list 1à2à3à4à5à6… becomes 2à1à4à3à6à5…
IMPORTANT: Your implementation must also work for circular lists where the tail is pointing back to the head of the list. You do not have to check if the tail points to an intermediate (non-head) element.
If you would like to solve the problem in C#, consider the following definitions:
public class Node
{
public int n; // value of element
public Node next; // pointer to next element in list
}
public Node swapPairs(Node head);
lee00863 1年前 已收到1个回答 举报

happyjoseph 幼苗

共回答了16个问题采纳率:100% 举报

....哦....so难~不过很具

1年前

3
可能相似的问题
Copyright © 2024 YULUCN.COM - 雨露学习互助 - 17 q. 0.069 s. - webmaster@yulucn.com