Docsity

Doubly Linked Lists: Inserting a Node into a Sorted List, Exercises of Aeronautical Engineering

Partial preview of the text

Download Doubly Linked Lists: Inserting a Node into a Sorted List and more Exercises Aeronautical Engineering in PDF only on Docsity!

CP5_

The problems in this problem set cover lectures C5 and C6.

a. What are doubly linked lists? What is the record declaration for a node in a doubly

linked list?

head

Figure 1. Sample Doubly Linked List

Doubly linked lists have two pointers instead of the single pointer seen in singly linked

lists. The pointers point to both the previous node in the list as well as the next node in

the list.

type Listnode is record Element : Elementtype; Next : Listptr; Prev : Listptr; -- this is the change made to singly linked lists end record;

b. Write an algorithm to insert a node into a sorted doubly linked list. Use a diagram to

show the sequence of operations that have to be performed to carry out the insertion step.

Hint: Extend the approach used in class/ notes for singly linked lists.

Preconditions:

1. User passes the list (called List) and the element to be inserted (called Element) to

the insert procedure

2. List is already sorted

Postconidtions:

1. Procedure returns the list with the element inserted in the correct position

2. List remains sorted

Algorithm:

Create three temporary Listptrs Current , Previous and NewNode

Previous := null

Current := List.Head;

NewNode := new Listnode;

NewNode.Element := Element

NewNode

NewNode.Next := Current

head Previous Current

NewNode.Prev := Previous

NewNode

head Previous Current

Previous.Next := NewNode

NewNode

head Previous Current

Current.Prev := NewNode

NewNode

head Previous Current

Figure 3. After Insertion Operation

c. Implement your algorithm as an Ada95 program.

Package Specification

GNAT 3.15p (20020523) Copyright 1992-2002 Free Software Foundation, Inc.

Checking: c:/docume~1/jayaka~1/mydocu~1/16070/code/doubly_linked_list.ads (source file time stamp: 2004-03-31 20:46:40)

  1. -- Specification for doubly-linked lists
  2. -- Specified: Jayakanth Srinivasan
  3. -- Last Modified: February 11, 2004

  4. package Doubly_Linked_List is
  5. subtype Elementtype is Integer;
  6. type Listnode;
  7. type Listptr is access Listnode;
  8. type Listnode is
  9. record
  10. Element : Elementtype;
  11. Next : Listptr;
  12. Prev : Listptr; -- this is the change made to singly linked lists
  13. end record;
  14. type List is
  15. record
  16. Head : Listptr;
  17. end record;