list-exercise

# list-exercise - } return; } 2. Reversing a Linked List...

This preview shows pages 1–4. Sign up to view the full content.

Class Exercise 1) Write a function that will split a linked list into two lists L1 and L2 such that, successive nodes go to different lists. (The first, third and all the other odd numbered nodes go to the first list, the second, fourth and all the other even numbered nodes go to the second list). 2) Write a function that will reverse the pointers of a linked list while traversing it only once.

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Answers 1. Splitting a linked list. void split(stuct node *head, struct node **L1, struct node ** L2) { struct node *p, *q; *L1 = head; if (*L1 != NULL) *L2 = head->next; else *L2 =NULL; p = head; while (p != NULL){ q = p->next; if (q!=NULL) p->next = q->next; p = q;

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: } return; } 2. Reversing a Linked List struct node * ReverseList(struct node *head) { struct node * p, *q, *temp; p = head; if (p!= NULL){ q = p->next; head->next = NULL; } else q=NULL; while (q!= NULL) { temp = q->next; q ->next = p; p = q; q = temp; } return p; } Recursive version struct node * reverse_list(struct node * head) { if (head == NULL) return NULL; else return(reverse(NULL, head)); } struct node * reverse (struct node * p, struct node *q) { struct node *t; if (q->next == NULL){ q->next = p; return q; } else { t = q->next; q->next = p; return(reverse (q, t)); } } Initial call: mylist = reverse_list(mylist);...
View Full Document

## This document was uploaded on 06/12/2011.

### Page1 / 4

list-exercise - } return; } 2. Reversing a Linked List...

This preview shows document pages 1 - 4. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online