JAVA算法问题,在一个List里,成对换位
给出一个包含node对象的list,publicclassNode{publicintn;//node的值publicNodenext;//list中的下一个Node,可...
给出一个包含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); 展开
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); 展开
2个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询