Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

Islamic University of Gaza Eng.

Jehad Aldahdooh
Faculty of Engineering DataStructure and Algorithms
Computer Engineering Dept. HW #1 Solution

R3.9: Describe a method for inserting an element at the beginning of a singly


linked list. Assume that the list does not have a sentinel header node, and instead
uses a variable head to reference the first node in the list.

Algorithm addFirst(Node v){

v.setNext(head);

head=v;

size++; Pseudo code

R3.10: Give an algorithm for finding the penultimate node in a singly linked list
where the last element is indicated by a null next reference.

Pseudo code

1
Chapter 3: Arrays, Linked lists, and Recursion Eng.Jehad Aldahdooh

R3.12: Describe a recursive algorithm for finding the maximum element in an


array A of n elements

Algorithm Max (A, m, n)


Input: An array A and the value of the last element m and the
size n.
Output: the maximum number in the array
if m<A[n-1]
m←A[n-1]
if n=1
return m Pseudo code
else
return Max(A, m, n-1)

C-3.7: Describe a fast recursive algorithm for reversing a singly linked list L, so
that the ordering of the nodes becomes opposite of what it was before.

Pseudo code

How to call it

2
Chapter 3: Arrays, Linked lists, and Recursion Eng.Jehad Aldahdooh

C3.9: Give a fast algorithm for concatenating two doubly linked lists Land M, with
header and trailer sentinel nodes, into a single list L'.

Pseudo code

C3.13: Describe a recursive method for converting a string of digits into the integer
it represents. For example, 1113531 11 represents the integer 13,531

int convert( string s){ string temp;

for(int count = 0; count < s.length(); count++){

if(s[count] != ' ') {

temp += s[count]; }

int n = temp.length() - 1;

if(temp.empty()) {

return 0;}

if(temp[0] == '-'){ return -convert(temp.substr(1, n--) ) ; }

if ( temp.length() == 1){ Pseudo code

if (isdigit(temp[0])) { return temp[0]- '0'; }

else { return 0; }

return convert(temp.substr(temp.length() - 1, 1 )) + convert(temp.substr(0,


n--) ) * 10 ;

3
Chapter 3: Arrays, Linked lists, and Recursion Eng.Jehad Aldahdooh

C3.18: Write a short recursive Java method that will rearrange an array of int
values so that all the even values appear before all the odd values.

‫مرفق مع الملف الكود‬

C3.18A.java

4
Chapter 3: Arrays, Linked lists, and Recursion Eng.Jehad Aldahdooh

‫طريقة تانية‬

‫مرفق مع الملف الكود‬

C3.18B.java

Extra Exercises

5
Chapter 3: Arrays, Linked lists, and Recursion Eng.Jehad Aldahdooh

C3.19: Write a short recursive Java method that takes a character string s and
outputs its reverse. So for example, the reverse of "pots&pans" would be
"snap&stop".

‫مرفق مع الملف الكود‬

Reverse.java

C-3.6 Give a recursive algorithm to compute the product of two positive integers,
m and n, using only addition and subtraction.

‫مرفق مع الملف الكود‬

Product.java

You might also like