CS210 Tutorial 2
Complete the following exercises pasted below (or reference to texbook)
Q1. Write code to duplicate an array of type strings.
Q2. Create class Node with (int id) (String Name) (double GPA) (Node next) as members. Write a tester program to add three students (provide your own details). Link all nodes so they can be accessed using a "head" pointer.
Q3. Give an algorithm to find the (node before the last) in a singly linked list. Use the Node class from Q2.
Q4. Modify the SList class to add a new method called addBeforeHead. This method adds a new node in the begining of the List. Use the Node class from Q2.
Q5. Write a addMiddle method in the SList class implementation that traverses to the middle of the List and inserts Node n. Make sure you connect the .next reference to the next node.
Q6. Write a findID method that traverses the List for a node containing id of a student. It returns pointer/reference to the Node.
Q7. Write a bringToFirst method that traverses the List for a node containing id of a student. It detaches this node from the list and attaches it to the Head of the List.
//Q1
public class Q1 {
public static void main(String [] args){
String [] S = {"hello","world","!"};
String [] D = duplicateString(S);
printString(D);
}
public static String [] duplicateString(String [] A)
{
String [] B = new String [A.length];
for(int i=0;i<A.length;i++)
B[i] = A[i];
return B;
}
public static void printString(String [] A)
{
for(int i=0;i<A.length;i++){
System.out.println(A[i]);
}
}
}
//Q2
class Node {
public int id;
public String name;
public double GPA;
public Node next;
public Node(){
id = 0;
name = "";
GPA = 0;
next = null;
}
}
public class Q2 {
public static void main(String [] args){
Node Head = new Node();
Head.id = 1;
Head.name = "Mohammad";
Head.GPA = 3.0;
Head.next = new Node();
Head.next.id = 2;
Head.next.name = "Ahmed";
Head.next.GPA = 3.3;
Head.next.next = new Node();
Head.next.next.id = 3;
Head.next.next.name = "Ali";
Head.next.next.GPA = 3.1;
}
}
//Q3
public Node nodeBeforeLast(SLL S)
{
Node itr = S.head;
for(int i=0;i<S.size();i++)
itr = itr.next;
return itr;
}
//Q4
public void addBeforeHead(int v)
{
Node N = new Node();
N.key = v;
N.next = head;
head = N;
size++;
}
//Q5
public void addMiddle(int v)
{
Node N = new Node();
N.key = v;
int mid = (size-1)/2 ;
Node itr = head;
for(int i=0;i < mid;i++)
itr=itr.next;
N.next=itr.next;
itr.next=N;
}
//Q6
public Node findID(int v)
{
Node itr = head;
while(itr!=null)
{
if(itr.id==v)
return itr;
itr = itr.next;
}
return null;
}
//Q7
public void bringToFirst(int v)
{
Node temp = head;
Node Prev = null;
while(temp.next!=null)
{
if(temp.id==v)
break;
Prev = temp;
temp=temp.next;
}
//detach temp from the list;
Prev.next=temp.next;
temp.next=head;
head=temp;
}
}