Set - 7

Question 11 :

Name some pure object oriented languages?

Answer :

Smalltalk, Java, Eiffel, Sather.


Question 12 :

How do you write a function that can reverse a linked-list?

Answer :

Answer1:

void reverselist(void){
	if(head==0)
		return;
	if(head-<next==0)
		return;
	if(head-<next==tail){
		head-<next = 0;
		tail-<next = head;
	}
	else{
		node* pre = head;
		node* cur = head-<next;
		node* curnext = cur-<next;
		head-<next = 0;
		cur-<next = head;

		for(; curnext!=0; ){
			cur-<next = pre;
			pre = cur;
			cur = curnext;
			curnext = curnext-<next;
		}
		curnext-<next = cur;
	}
}

Answer2:

node* reverselist(node* head){
	if(0==head || 0==head->next) 
		//if head->next ==0 should return head instead of 0;
		return 0;
	{
		node* prev = head;
		node* curr = head->next;
		node* next = curr->next;
		for(; next!=0; ){
			curr->next = prev;
			prev = curr;
			curr = next;
			next = next->next;
		}
		curr->next = prev;
		head->next = 0;
		head = curr;
	}
	return head;
}

 


Question 13 :

Detemine the code below, tell me exectly how many times is the operation sum++ performed ? 

Answer :

for ( i = 0; i < 100; i++ )
for ( j = 100; j > 100 - i; j–)
sum++;

(99 * 100)/2 = 4950
The sum++ is performed 4950 times.


Question 14 :

What is deadlock?

Answer :

Deadlock is a situation when two or more processes prevent each other from running. Example: if T1 is holding x and waiting for y to be free and T2 holding y and waiting for x to be free deadlock happens.


Question 15 :

What is semaphore?

Answer :

Semaphore is a special variable, it has two methods: up and down. Semaphore performs atomic operations, which means ones a semaphore is called it can not be interrupted. 

The internal counter (= #ups - #downs) can never be negative. If you execute the "down" method when the internal counter is zero, it will block until some other thread calls the "up" method. Semaphores are use for thread synchronization.