Java 通过递归交换LinkedList中的第1和第3个元素数据

Java 通过递归交换LinkedList中的第1和第3个元素数据,java,recursion,data-structures,linked-list,Java,Recursion,Data Structures,Linked List,我已将节点定义为 class Node { int data ; Node next ; Node(int data) { this.data = data ; next = null ; } } 我写递归代码有困难。迭代工作得很好。这是我的密码。其思想是检查列表是否为空。如果没有,则检查第三个元素是否存在。如果有,则与之交换数据。然后转到下一个节点,即第四个节点。然后为下一个节点调用递归函数。 我的想法怎么了 publi

我已将节点定义为

class Node
{
    int data ;
    Node next ;
    Node(int data)
    {
        this.data = data ;
        next = null ;
    }
}
我写递归代码有困难。迭代工作得很好。这是我的密码。其思想是检查列表是否为空。如果没有,则检查第三个元素是否存在。如果有,则与之交换数据。然后转到下一个节点,即第四个节点。然后为下一个节点调用递归函数。 我的想法怎么了

public class change_1_and_3 {

Node head ;

Node changeUtil(Node head)
{
    Node temp = head ;
    if(head==null)
        return head ;
    if(temp.next.next!=null)
    {
        int res = temp.data ;
        temp.data = temp.next.next.data;
        temp.next.next.data = res ;
        temp = temp.next.next ;
    }
    else
        return head ;
    if(temp.next!=null)
        temp = temp.next ;
    else
        return head ;
    return changeUtil(temp);
}

void change()
{
    Node temp = changeUtil(head);
    while(temp!=null)
    {
        System.out.println(temp.data);
        temp = temp.next ;
    }
}

}

假设您只需要交换每个第一个和第三个节点的数据,保持节点列表本身不变,您可以尝试以下操作:

Node changeUtil(Node head)
{
  // Ignore if not both the 1st and 3rd node exist
  // This is were your code fails!!
  if ((head == null) || (head.next == null) || (head.next.next == null))
    return (head);

  // Point to 3rd node
  Node third;
  third = head.next.next;

  // Swap contents
  int temp;
  temp = head.data;
  head.data = third.data;
  third.data = temp;

  // Same stuff starting from 4th node
  changeUtil(third.next);

  // Done
  return (head);

} // changeUtil

对于初学者,这里的temp.next不能为null:if(temp.next.next!=null)?您只检查了temp。是否也可以发布输入和输出链接列表?您应该只交换第一个和第三个节点的数据,还是应该交换节点?