【问题标题】:Swap every 1st and 3rd element data in LinkedList by Recursion通过递归交换 LinkedList 中的每个第一个和第三个元素数据
【发布时间】:2018-06-05 11:25:00
【问题描述】:

我已将节点定义为

class Node
{
    int data ;
    Node next ;
    Node(int data)
    {
        this.data = data ;
        next = null ;
    }
}

我在编写递归代码时遇到了困难。迭代工作得很好。这是我的代码。这个想法是检查列表是否为空。如果没有,则检查第三个元素是否存在。如果是,则与之交换数据。然后转到下一个节点,即第 4 个节点。然后为下一个节点调用递归函数。 我的想法有什么问题?

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 ;
    }
}

}

【问题讨论】:

  • 对于初学者来说,这里的 temp.next 不能为空:if(temp.next.next!=null)?您只检查了温度。
  • 能不能也贴一下输入输出链表?
  • 是交换第一个和第三个节点的数据还是交换节点?

标签: java recursion data-structures linked-list


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-22
    • 2022-11-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多