Computer Science, asked by vanshbansal6086, 1 year ago

Given a sentence, write a program to arrange and print the words in the sentence such that the last letter of the previous word is same as the first letter of the next word. Print the arranged sentence. Sample Input - first impulse gruff toni Sample Output - gruff first toni impulse

Answers

Answered by RohitSaketi
5
here it is..package rohit;

import java.util.Scanner;

public class Type_conversions {
public static void main(String args[])
{

Scanner scan = new Scanner(System.in);

int n = Integer.parseInt(scan.nextLine());
// System.out.println(n);
//Create a string array to store the names of your friends
String s[] = new String[n];
for (int i = 0; i < s.length; i++) {

s[i] = scan.nextLine();
}
int found=0,i=0;
for(i=0;i<s.length;i++)
{
for(int j=0;j<s.length;j++)
{
if(s[i].charAt(s[i].length()-1)==s[j].charAt(0))
{
found=1;
break;
}
}
if(found==0)
break;
else
found=0;
}
int arr[]=new int[s.length];
arr[s.length-1]=i;
int p=s.length-1;
for(int k=0;i<s.length;i++)
{
for(int j=0;j<s.length;j++)
{
if(s[arr[p]].charAt(0)==s[j].charAt(s[j].length()-1))
{
p=p-1;
arr[p]=j;
break;
}
}
}
for(i=0;i<s.length;i++)
{
System.out.print(s[arr[i]]+" ");
}
}

}
Attachments:
Similar questions