简体   繁体   中英

Swap every 1st and 3rd element data in LinkedList by Recursion

I have defined the node as

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

I am having difficulty writing the recursive code. The iterative works just fine. This is my code. The idea is to check if list is null. If not then check if 3rd element exists. If it does, swap data with it. Then go to the next node which is the 4th one. Then call recursive function for the next node. What is wrong with my idea ?

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

}

Supposing you just need to swap the data of each 1st and 3rd node, leaving the list of nodes itself unchanged, you might try the following:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM