0
public class Traverse {

    public static void main(String[] args) {
        Node head = new Node(10);
        head.next = new Node(20);
        head.next.next = new Node(30);
        head.next.next.next = new Node(40);
        head.next.next.next.next = new Node(50);
        printList(head);
    }

    public static void printList(Node head) {
        Node curr = head;

        while (curr != null) {
            System.out.print(curr.data);
            curr = curr.next;
        }
    }
}

The output is:

 10,20,30,40,50, 

I don't want the last commma (,).

I am asking this because in a company interview a similar question was asked and logically the traversal is correct but because of the last comma 1 test case failed. I know it's lame but a blunder so the output should be:

10,20,30,40,50
andrewJames
  • 19,570
  • 8
  • 19
  • 51
  • 4
    You could change the `toString` method in your `Node` class so that it doesn't print the comma if there's no `next` element. In fact, you could even change it so that it calls the `toString` method on `next` recursively; and that way, you wouldn't need a loop in `printList`. – Dawood ibn Kareem Jan 10 '23 at 19:14
  • 2
    You can research similar questions - for example: [Avoid printing the last comma](https://stackoverflow.com/q/9991799/12567365) or [any of these](https://www.google.com/search?q=don't+print+final+comma+site:stackoverflow.com) for more ideas which can be adapted to your specific situation. – andrewJames Jan 10 '23 at 19:16
  • 1
    *"so the output is 10,20,30,40,50, "*: eh, not it isn't. There is no comma output in your code. – trincot Jan 10 '23 at 19:19
  • @trincot not with the code shown. The question is incomplete as it does not include a [mre]. `Node`, or whatever type `Node#data` is, could add the comma in their `toString()` method. – knittl Jan 10 '23 at 19:24
  • @knittl, the question is to the OP. – trincot Jan 10 '23 at 19:24

1 Answers1

0

The comma is printed for the same number of times as the numbers. To prevent the last comma from getting printed, a simple if condition should do the trick.

 public static void printList(Node head) {
        Node curr = head;

        while (curr != null) {

            System.out.print(curr.data);

            if(curr.next != null)
                System.out.print(",");
           
            curr = curr.next;
        }
    }

This condition checks whether there is a number after the current number. If there is, a comma is printed, otherwise the comma is not printed for the last number.

P.S Upvote if it helped!