Free Essay

Mfrkkwl

In:

Submitted By hassandayo
Words 7409
Pages 30
An array is defined as a sequence of objects of the same data type. All the elements of an array are either of type int (whole numbers), or all of them are of type char, or all of them are of floating decimal point type, etc. An array cannot have a mixture of different data types as its elements. Also, array elements cannot be functions; however, they may be pointers to functions. In computer memory, array elements are stored in a sequence of adjacent memory blocks. Since all the elements of an array are of same data type, the memory blocks allocated to elements of an array are also of same size. Each element of an array occupies one block of memory. The size of memory blocks allocated depends on the data type and it is same as for different data types. Often, we have to deal with groups of objects of same type such as names of persons, instrument readings in an experiment, roll numbers of students, and so on. These groups can be conveniently represented as elements of arrays.

The declaration of array includes the type of array that is the type of value we are going to store in it, the array name and maximum number of elements.

Examples:

short val[200];

val[12] = 5;

Declaration & Data Types

Arrays have the same data types as variables, i.e., short, long, float etc. They are similar to variables: they can either be declared global or local. They are declared by the given syntax:

Datatype array_name [dimensions] = {element1,element2,….,element}

The declaration form of one-dimensional array is

Data_type array_name [size];

The following declares an array called ‘numbers’ to hold 5 integers and sets the first and last elements. C arrays are always indexed from 0. So the first integer in ‘numbers’ array is numbers[0] and the last is numbers[4].

int numbers [5]; numbers [0] = 1; // set first element numbers [4] = 5;

This array contains 5 elements. Any one of these elements may be referred to by giving the name of the array followed by the position number of the particular element in square brackets ([ ]). The first element in every array is the zeroth element. Thus, the first element of array ‘numbers’ is referred to as numbers[ 0 ], the second element of array ‘numbers’ is referred to as numbers[ 1 ], the fifth element of array ‘numbers’ is referred to as numbers[ 4 ], and, in general, the nth element of array ‘numbers’ is referred to as numbers[ n - 1 ].

Arrays are linear data structure while linked lists are linear and non-linear in case of linked list :-from point of access strategy it is linear and from point of storage strategy it is non linear
In array we follow static memory allocation. i.e we assign memory to the particular element in advance.
In linked list -> dynamic memory allocation. i.e we assign memory to the particular element at run-time.. hence we reserve only the amount of memory which is required. There is no problem of memory shortage or wastage, in linked list. Which we very frequently come across in the arrays..

Linked List vs Array
Difficulty Level: Rookie

Both Arrays and Linked List can be used to store linear data of similar types, but they both have some advantages and disadvantages over each other.

Following are the points in favour of Linked Lists.

(1) The size of the arrays is fixed: So we must know the upper limit on the number of elements in advance. Also, generally, the allocated memory is equal to the upper limit irrespective of the usage, and in practical uses, upper limit is rarely reached.

(2) Inserting a new element in an array of elements is expensive, because room has to be created for the new elements and to create room existing elements have to shifted.

For example, suppose we maintain a sorted list of IDs in an array id[].

id[] = [1000, 1010, 1050, 2000, 2040, …..].

And if we want to insert a new ID 1005, then to maintain the sorted order, we have to move all the elements after 1000 (excluding 1000).

Deletion is also expensive with arrays until unless some special techniques are used. For example, to delete 1010 in id[], everything after 1010 has to be moved.

So Linked list provides following two advantages over arrays
1) Dynamic size
2) Ease of insertion/deletion

Linked lists have following drawbacks:
1) Random access is not allowed. We have to access elements sequentially starting from the first node. So we cannot do binary search with linked lists.
2) Extra memory space for a pointer is required with each element of the list.
3) Arrays have better cache locality that can make a pretty big difference in performance.

Please also see this thread.

References: http://cslibrary.stanford.edu/103/LinkedListBasics.pdf Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

In computer science, a linked list is a data structure consisting of a group of nodes which together represent a sequence. Under the simplest form, each node is composed of a data and a reference (in other words, a link) to the next node in the sequence; more complex variants add additional links. This structure allows for efficient insertion or removal of elements from any position in the sequence. A linked list whose nodes contain two fields: an integer value and a link to the next node. The last node is linked to a terminator used to signify the end of the list. Linked lists are among the simplest and most common data structures. They can be used to implement several other common abstract data types, including lists (the abstract data type),stacks, queues, associative arrays, and S-expressions, though it is not uncommon to implement the other data structures directly without using a list as the basis of implementation.
The principal benefit of a linked list over a conventional array is that the list elements can easily be inserted or removed without reallocation or reorganization of the entire structure because the data items need not be stored contiguously in memory or on disk, while an array has to be declared in the source code, before compiling and running the program. Linked lists allow insertion and removal of nodes at any point in the list, and can do so with a constant number of operations if the link previous to the link being added or removed is maintained during list traversal. On the other hand, simple linked lists by themselves do not allow random access to the data, or any form of efficient indexing. Thus, many basic operations — such as obtaining the last node of the list (assuming that the last node is not maintained as separate node reference in the list structure), or finding a node that contains a given datum, or locating the place where a new node should be inserted — may require sequential scanning of most or all of the list elements.
The advantages and disadvantages of using linked lists are given below.
Advantages[edit]Linked lists are a dynamic datastructure, allocating theneeded memory while the programis running.Insertion and deletion nodeoperations are easilyimplemented in a linked list.Linear data structures such asstacks and queues are easilyexecuted with a linked list.They can reduce access time andmay expand in real time withoutmemory overhead.
Disadvantages[edit]They have a tendency to wastememory due topointersrequiring extra storage space.Nodes in a linked list must beread in order from thebeginning as linked lists areinherentlysequential access.Nodes are stored incontiguously, greatly increasing the timerequired to access individualelements within the list.Difficulties arise in linkedlists when it comes to reversetraversing. Singly linked listsare extremely difficult tonavigate backwards, and whiledoubly linked lists aresomewhat easier to read, memoryis wasted in allocating spacefor a back pointer.
History[edit]Linked lists were developed in1955–1956 byAllen Newell, Cliff Shaw andHerbert A. SimonatRAND Corporation as theprimarydata structure fortheirInformation ProcessingLanguage. IPL was used by theauthors to develop severalearlyartificial intelligenceprograms, including the LogicTheory Machine, theGeneralProblem Solver, and a computerchess program. Reports on theirwork appeared in IRETransactions on InformationTheory in 1956, and severalconference proceedings from1957 to 1959, includingProceedings of the WesternJoint Computer Conference in1957 and 1958, and InformationProcessing (Proceedings of thefirstUNESCO InternationalConference on InformationProcessing) in 1959. The now-classic diagram consisting ofblocks representing list nodeswith arrows pointing tosuccessive list nodes appearsin "Programming the LogicTheory Machine" by Newell andShaw in Proc. WJCC, February1957. Newell and Simon wererecognized with the ACMTuringAward in 1975 for having "madebasic contributions toartificial intelligence, thepsychology of human cognition,and list processing". Theproblem ofmachine translationfornatural language processingledVictor Yngve atMassachusetts Institute ofTechnology (MIT) to use linkedlists as data structures in hisCOMIT programming language forcomputer research in the fieldoflinguistics. A report onthis language entitled "Aprogramming language formechanical translation"appeared in MechanicalTranslation in 1958.LISP, standing for listprocessor, was created byJohnMcCarthy in 1958 while he wasat MIT and in 1960 he publishedits design in a paper in theCommunications of the ACM, entitled "Recursive Functionsof Symbolic Expressions andTheir Computation by Machine,Part I". One of LISP's majordata structures is the linkedlist.By the early 1960s, the utilityof both linked lists andlanguages which use thesestructures as their primarydata representation was wellestablished. Bert Green of theMIT Lincoln Laboratorypublished a review articleentitled "Computer languagesfor symbol manipulation" in IRETransactions on Human Factorsin Electronics in March 1961which summarized the advantagesof the linked list approach. Alater review article, "AComparison of list-processingcomputer languages" by Bobrowand Raphael, appeared inCommunications of the ACM inApril 1964.Several operating systemsdeveloped byTechnical SystemsConsultants (originally of WestLafayette Indiana, and later ofChapel Hill, North Carolina)used singly linked lists asfile structures. A directoryentry pointed to the firstsector of a file, andsucceeding portions of the filewere located by traversingpointers. Systems using thistechnique included Flex (fortheMotorola 6800 CPU), mini-Flex (same CPU), and Flex9 (forthe Motorola 6809 CPU). Avariant developed by TSC forand marketed by Smoke SignalBroadcasting in California,used doubly linked lists in thesame manner.The TSS/360 operating system,developed by IBM for the System360/370 machines, used a doublelinked list for their filesystem catalog. The directorystructure was similar to Unix,where a directory could containfiles and/or other directoriesand extend to any depth. Autility flea was created to fixfile system problems after acrash, since modified portionsof the file catalog weresometimes in memory when acrash occurred. Problems weredetected by comparing theforward and backward links forconsistency. If a forward linkwas corrupt, then if a backwardlink to the infected node wasfound, the forward link was setto the node with the backwardlink. A humorous comment in thesource code where this utilitywas invoked stated "Everyoneknows a flea collar gets rid ofbugs in cats".
Basic concepts and nomenclature[edit]Each record of a linked list isoften called anelement ornode.The field of each node thatcontains the address of thenext node is usually called thenext link ornext pointer. Theremaining fields are known asthedata, information, value, cargo, orpayload fields.Thehead of a list is its firstnode. Thetail of a list mayrefer either to the rest of thelist after the head, or to thelast node in the list. InLispand some derived languages, thenext node may be called thecdr(pronouncedcould-er) of thelist, while the payload of thehead node may be called thecar.
Singly linked list[edit]Singly linked lists containnodes which have a data fieldas well as anext field, whichpoints to the next node in lineof nodes. Operations that canbe performed on singly linkedlists include insertion,deletion and traversal.A singly linked list whose nodescontain two fields: an integer valueand a link to the next node
Doubly linked list[edit]Main article:Doubly linkedlistIn adoubly linked list, eachnode contains, besides the next-node link, a second link fieldpointing to theprevious nodein the sequence. The two linksmay be calledforward(s) andbackwards, ornext andprev(previous).A doubly linked list whose nodescontain three fields: an integer value,the link forward to the next node, andthe link backward to the previous nodeA technique known asXOR-linking allows a doubly linkedlist to be implemented using asingle link field in each node.However, this techniquerequires the ability to do bitoperations on addresses, andtherefore may not be availablein some high-level languages.
Multiply linked list[edit]In amultiply linked list, eachnode contains two or more linkfields, each field being usedto connect the same set of datarecords in a different order (e.g., by name, by department, bydate of birth, etc.). Whiledoubly linked lists can be seenas special cases of multiplylinked list, the fact that thetwo orders are opposite to eachother leads to simpler and moreefficient algorithms, so theyare usually treated as aseparate case.Circular Linked list[edit]In the lastnode of a list, thelink field often contains anull reference, a special valueused to indicate the lack offurther nodes. A less commonconvention is to make it pointto the first node of the list;in that case the list is saidto be 'circular' or 'circularlylinked'; otherwise it is saidto be 'open' or 'linear'.A circular linked listIn the case of a circulardoubly linked list, the onlychange that occurs is that theend, or "tail", of the saidlist is linked back to thefront, or "head", of the listand vice versa.
Sentinel nodes[edit]Main article:Sentinel nodeIn some implementations, anextrasentinel ordummy nodemay be added before the firstdata record and/or after thelast one. This conventionsimplifies and accelerates somelist-handling algorithms, byensuring that all links can besafely dereferenced and thatevery list (even one thatcontains no data elements)always has a "first" and "last"node.
Empty lists[edit]An empty list is a list thatcontains no data records. Thisis usually the same as sayingthat it has zero nodes. Ifsentinel nodes are being used,the list is usually said to beempty when it has only sentinelnodes.Hash linking[edit]The link fields need not bephysically part of the nodes.If the data records are storedin an array and referenced bytheir indices, the link fieldmay be stored in a separatearray with the same indices asthe data records.
List handles[edit]Since a reference to the firstnode gives access to the wholelist, that reference is oftencalled theaddress, pointer, orhandle of the list. Algorithmsthat manipulate linked listsusually get such handles to theinput lists and return thehandles to the resulting lists.In fact, in the context of suchalgorithms, the word "list"often means "list handle". Insome situations, however, itmay be convenient to refer to alist by a handle that consistsof two links, pointing to itsfirst and last nodes.
Combining alternatives[edit]The alternatives listed abovemay be arbitrarily combined inalmost every way, so one mayhave circular doubly linkedlists without sentinels,circular singly linked listswith sentinels, etc.Tradeoffs[edit]As with most choices incomputer programming and design, no method is well suited toall circumstances. A linkedlist data structure might workwell in one case, but causeproblems in another. This is alist of some of the commontradeoffs involving linked liststructures.
Linked lists vs. dynamic arrays[edit]A dynamic array is a datastructure that allocates allelements contiguously in memory, and keeps a count of thecurrent number of elements. Ifthe space reserved for thedynamic array is exceeded, itis reallocated and (possibly)copied, an expensive operation.Linked lists have severaladvantages over dynamic arrays.Insertion or deletion of anelement at a specific point ofa list, assuming that we haveindexed a pointer to the node (before the one to be removed,or before the insertion point)already, is a constant-timeoperation (otherwise withoutthis reference it is O(n)),whereas insertion in a dynamicarray at random locations willrequire moving half of theelements on average, and allthe elements in the worst case.While one can "delete" anelement from an array inconstant time by somehowmarking its slot as "vacant",this causesfragmentation thatimpedes the performance ofiteration.Moreover, arbitrarily manyelements may be inserted into alinked list, limited only bythe total memory available;while a dynamic array willeventually fill up itsunderlying array data structureand will have to reallocate —an expensive operation, onethat may not even be possibleif memory is fragmented,although the cost ofreallocation can be averagedover insertions, and the costof an insertion due toreallocation would still beamortized O(1). This helps withappending elements at the array's end, but inserting into (orremoving from) middle positionsstill carries prohibitive costsdue to data moving to maintaincontiguity. An array from whichmany elements are removed mayalso have to be resized inorder to avoid wasting too muchspace.On the other hand, dynamicarrays (as well as fixed-sizearray data structures) allowconstant-timerandom access, while linked lists allow onlysequential access to elements.Singly linked lists, in fact,can be easily traversed in onlyone direction. This makeslinked lists unsuitable forapplications where it's usefulto look up an element by itsindex quickly, such asheapsort. Sequential access on arraysand dynamic arrays is alsofaster than on linked lists onmany machines, because theyhave optimallocality ofreference and thus make gooduse of data caching.Another disadvantage of linkedlists is the extra storageneeded for references, whichoften makes them impracticalfor lists of small data itemssuch ascharacters orbooleanvalues, because the storageoverhead for the links mayexceed by a factor of two ormore the size of the data. Incontrast, a dynamic arrayrequires only the space for thedata itself (and a very smallamount of control data).[note 1]It can also be slow, and with anaïve allocator, wasteful, toallocate memory separately foreach new element, a problemgenerally solved usingmemorypools.Some hybrid solutions try tocombine the advantages of thetwo representations.Unrolledlinked lists store severalelements in each list node,increasing cache performancewhile decreasing memoryoverhead for references.CDRcoding does both these as well,by replacing references withthe actual data referenced,which extends off the end ofthe referencing record.A good example that highlightsthe pros and cons of usingdynamic arrays vs. linked listsis by implementing a programthat resolves theJosephusproblem. The Josephus problemis an election method thatworks by having a group ofpeople stand in a circle.Starting at a predeterminedperson, you count around thecirclen times. Once you reachthenth person, take them outof the circle and have themembers close the circle. Thencount around the circle thesamen times and repeat theprocess, until only one personis left. That person wins theelection. This shows thestrengths and weaknesses of alinked list vs. a dynamic array, because if you view thepeople as connected nodes in acircular linked list then itshows how easily the linkedlist is able to delete nodes (as it only has to rearrange thelinks to the different nodes).However, the linked list willbe poor at finding the nextperson to remove and will needto search through the listuntil it finds that person. Adynamic array, on the otherhand, will be poor at deletingnodes (or elements) as itcannot remove one node withoutindividually shifting all theelements up the list by one.However, it is exceptionallyeasy to find thenth person inthe circle by directlyreferencing them by theirposition in the array.Thelist ranking problemconcerns the efficientconversion of a linked listrepresentation into an array.Although trivial for aconventional computer, solvingthis problem by aparallelalgorithm is complicated andhas been the subject of muchresearch.A balanced tree has similarmemory access patterns andspace overhead to a linked listwhile permitting much moreefficient indexing, taking O(log n) time instead of O(n) fora random access. However,insertion and deletionoperations are more expensivedue to the overhead of treemanipulations to maintainbalance. Schemes exist fortrees to automatically maintainthemselves in a balanced state:AVL trees orred-black trees.
Singly linked linear lists vs.other lists[edit]While doubly linked and/orcircular lists have advantagesover singly linked linear lists, linear lists offer someadvantages that make thempreferable in some situations.A singly linked linear list isa recursive data structure,because it contains a pointerto asmaller object of the sametype. For that reason, manyoperations on singly linkedlinear lists (such asmergingtwo lists, or enumerating theelements in reverse order)often have very simplerecursive algorithms, muchsimpler than any solution usingiterative commands. While thoserecursive solutions can beadapted for doubly linked andcircularly linked lists, theprocedures generally need extraarguments and more complicatedbase cases.Linear singly linked lists alsoallowtail-sharing, the use ofa common final portion of sub-list as the terminal portion oftwo different lists. Inparticular, if a new node isadded at the beginning of alist, the former list remainsavailable as the tail of thenew one — a simple example of apersistent data structure. Again, this is not true withthe other variants: a node maynever belong to two differentcircular or doubly linked lists.In particular, end-sentinelnodes can be shared amongsingly linked non-circularlists. The same end-sentinelnode may be used forevery suchlist. InLisp, for example,every proper list ends with alink to a special node, denotedbynil or(), whoseCAR andCDR links point to itself.Thus a Lisp procedure cansafely take theCAR orCDR ofany list.The advantages of the fancyvariants are often limited tothe complexity of thealgorithms, not in theirefficiency. A circular list, inparticular, can usually beemulated by a linear listtogether with two variablesthat point to the first andlast nodes, at no extra cost.Doubly linked vs. singly linked[edit]Double-linked lists requiremore space per node (unless oneusesXOR-linking), and theirelementary operations are moreexpensive; but they are ofteneasier to manipulate becausethey allow fast and easysequential access to the listin both directions. In a doublylinked list, one can insert ordelete a node in a constantnumber of operations given onlythat node's address. To do thesame in a singly linked list,one must have theaddress ofthe pointer to that node, whichis either the handle for thewhole list (in case of thefirst node) or the link fieldin theprevious node. Somealgorithms require access inboth directions. On the otherhand, doubly linked lists donot allow tail-sharing andcannot be used aspersistentdata structures.Circularly linked vs. linearlylinked[edit]A circularly linked list may bea natural option to representarrays that are naturallycircular, e.g. the corners of apolygon, a pool ofbuffers thatare used and released inFIFO ("first in, first out") order,or a set of processes thatshould betime-shared inround-robin order. In theseapplications, a pointer to anynode serves as a handle to thewhole list.With a circular list, a pointerto the last node gives easyaccess also to the first node,by following one link. Thus, inapplications that requireaccess to both ends of the list(e.g., in the implementation ofa queue), a circular structureallows one to handle thestructure by a single pointer,instead of two.A circular list can be splitinto two circular lists, inconstant time, by giving theaddresses of the last node ofeach piece. The operationconsists in swapping thecontents of the link fields ofthose two nodes. Applying thesame operation to any two nodesin two distinct lists joins thetwo list into one. Thisproperty greatly simplifiessome algorithms and datastructures, such as thequad-edge andface-edge.The simplest representation foran emptycircular list (whensuch a thing makes sense) is anull pointer, indicating thatthe list has no nodes. Withoutthis choice, many algorithmshave to test for this specialcase, and handle it separately.By contrast, the use of null todenote an emptylinear list ismore natural and often createsfewer special cases.Using sentinel nodes[edit]Sentinel node may simplifycertain list operations, byensuring that the next and/orprevious nodes exist for everyelement, and that even emptylists have at least one node.One may also use a sentinelnode at the end of the list,with an appropriate data field,to eliminate some end-of-listtests. For example, whenscanning the list looking for anode with a given valuex, setting the sentinel's datafield tox makes it unnecessaryto test for end-of-list insidethe loop. Another example isthe merging two sorted lists:if their sentinels have datafields set to +∞, the choice ofthe next output node does notneed special handling for emptylists.However, sentinel nodes use upextra space (especially inapplications that use manyshort lists), and they maycomplicate other operations (such as the creation of a newempty list).However, if the circular listis used merely to simulate alinear list, one may avoid someof this complexity by adding asingle sentinel node to everylist, between the last and thefirst data nodes. With thisconvention, an empty listconsists of the sentinel nodealone, pointing to itself viathe next-node link. The listhandle should then be a pointerto the last data node, beforethe sentinel, if the list isnot empty; or to the sentinelitself, if the list is empty.The same trick can be used tosimplify the handling of adoubly linked linear list, byturning it into a circulardoubly linked list with asingle sentinel node. However,in this case, the handle shouldbe a single pointer to thedummy node itself.[5]Linked list operations[edit]When manipulating linked listsin-place, care must be taken tonot use values that you haveinvalidated in previousassignments. This makesalgorithms for inserting ordeleting linked list nodessomewhat subtle. This sectiongivespseudocode for adding orremoving nodes from singly,doubly, and circularly linkedlists in-place. Throughout wewill usenull to refer to anend-of-list marker orsentinel, which may be implemented in anumber of ways.Linearly linked lists[edit]Singly linked lists[edit]Our node data structure willhave two fields. We also keep avariablefirstNode which alwayspoints to the first node in thelist, or isnull for an emptylist.recordNode{data;// The data beingstored in the nodeNode next// Areference to the next node,null for last node}recordList{Node firstNode// points tofirst node of list; null forempty list}Traversal of a singly linkedlist is simple, beginning atthe first node and followingeachnext link until we come tothe end:node := list.firstNodewhile node not null(do something with node.data)node := node.nextThe following code inserts anode after an existing node ina singly linked list. Thediagram shows how it works.Inserting a node before anexisting one cannot be donedirectly; instead, one mustkeep track of the previous nodeand insert a node after it.function insertAfter(Node node,Node newNode)// insert newNodeafter nodenewNode.next := node.nextnode.next := newNodeInserting at the beginning ofthe list requires a separatefunction. This requiresupdatingfirstNode.function insertBeginning(Listlist,Node newNode)// insertnode before current first nodenewNode.next := list.firstNodelist.firstNode := newNodeSimilarly, we have functionsfor removing the nodeafter a given node, and for removing anode from the beginning of thelist. The diagram demonstratesthe former. To find and removea particular node, one mustagain keep track of theprevious element.function removeAfter(Node node)// remove node past this oneobsoleteNode := node.nextnode.next := node.next.nextdestroy obsoleteNodefunction removeBeginning(Listlist)// remove first nodeobsoleteNode := list.firstNodelist.firstNode := list.firstNode.next// point pastdeleted nodedestroy obsoleteNodeNotice thatremoveBeginning()setslist.firstNode tonullwhen removing the last node inthe list.Since we can't iteratebackwards, efficientinsertBefore orremoveBeforeoperations are not possible.Appending one linked list toanother can be inefficientunless a reference to the tailis kept as part of the Liststructure, because we musttraverse the entire first listin order to find the tail, andthen append the second list tothis. Thus, if two linearlylinked lists are each of length, list appending hasasymptotic time complexity of. In the Lisp family oflanguages, list appending isprovided by theappendprocedure.Many of the special cases oflinked list operations can beeliminated by including a dummyelement at the front of thelist. This ensures that thereare no special cases for thebeginning of the list andrenders bothinsertBeginning()andremoveBeginning()unnecessary. In this case, thefirst useful data in the listwill be found atlist.firstNode.next.Circularly linked list[edit]In a circularly linked list,all nodes are linked in acontinuous circle, withoutusingnull. For lists with afront and a back (such as aqueue), one stores a referenceto the last node in the list.Thenext node after the lastnode is the first node.Elements can be added to theback of the list and removedfrom the front in constant time.Circularly linked lists can beeither singly or doubly linked.Both types of circularly linkedlists benefit from the abilityto traverse the full listbeginning at any given node.This often allows us to avoidstoringfirstNode andlastNode, although if the list may beempty we need a specialrepresentation for the emptylist, such as alastNodevariable which points to somenode in the list or isnull ifit's empty; we use such alastNode here. Thisrepresentation significantlysimplifies adding and removingnodes with a non-empty list,but empty lists are then aspecial case.Algorithms[edit]Assuming thatsomeNode is somenode in a non-empty circularsingly linked list, this codeiterates through that liststarting withsomeNode:function iterate(someNode)if someNode ≠nullnode := someNodedodo something with node.valuenode := node.nextwhile node ≠ someNodeNotice that the test "whilenode ≠ someNode" must be at theend of the loop. If the testwas moved to the beginning ofthe loop, the procedure wouldfail whenever the list had onlyone node.This function inserts a node "newNode" into a circular linkedlist after a given node "node".If "node" is null, it assumesthat the list is empty.function insertAfter(Node node,Node newNode)if node =nullnewNode.next := newNodeelsenewNode.next := node.nextnode.next := newNodeSuppose that "L" is a variablepointing to the last node of acircular linked list (or nullif the list is empty). Toappend "newNode" to theend ofthe list, one may doinsertAfter(L, newNode)L := newNodeTo insert "newNode" at thebeginning of the list, one maydoinsertAfter(L, newNode)if L =nullL := newNodeLinked lists using arrays ofnodes[edit]Languages that do not supportany type ofreference can stillcreate links by replacingpointers with array indices.The approach is to keep anarray ofrecords, where eachrecord has integer fieldsindicating the index of thenext (and possibly previous)node in the array. Not allnodes in the array need be used. If records are also notsupported,parallel arrays canoften be used instead.As an example, consider thefollowing linked list recordthat uses arrays instead ofpointers:recordEntry {integer next;// index of nextentry in arrayinteger prev;// previous entry(if double-linked)string name;real balance;}By creating an array of thesestructures, and an integervariable to store the index ofthe first element, a linkedlist can be built:integer listHeadEntry Records[1000]Links between elements areformed by placing the arrayindex of the next (or previous)cell into the Next or Prevfield within a given element.For example:IndexNextPrevNameBalance014Jones, John123.451-10Smith, Joseph234.562 (listHead)4-1Adams, Adam0.003Ignore, Ignatius999.99402Another, Anita876.54567In the above example,ListHeadwould be set to 2, the locationof the first entry in the list.Notice that entry 3 and 5through 7 are not part of thelist. These cells are availablefor any additions to the list.By creating aListFree integervariable, afree list could becreated to keep track of whatcells are available. If allentries are in use, the size ofthe array would have to beincreased or some elementswould have to be deleted beforenew entries could be stored inthe list.The following code wouldtraverse the list and displaynames and account balance:i := listHeadwhile i ≥ 0// loop through thelistprint i, Records[i].name,Records[i].balance// printentryi := Records[i].nextWhen faced with a choice, theadvantages of this approachinclude:The linked list is relocatable,meaning it can be moved aboutin memory at will, and it canalso be quickly and directlyserialized for storage on diskor transfer over a network.Especially for a small list,array indexes can occupysignificantly less space than afull pointer on manyarchitectures.Locality of reference can beimproved by keeping the nodestogether in memory and byperiodically rearranging them,although this can also be donein a general store.Naïvedynamic memory allocatorscan produce an excessive amountof overhead storage for eachnode allocated; almost noallocation overhead is incurredper node in this approach.Seizing an entry from a pre-allocated array is faster thanusing dynamic memory allocationfor each node, since dynamicmemory allocation typicallyrequires a search for a freememory block of the desiredsize.This approach has one maindisadvantage, however: itcreates and manages a privatememory space for its nodes.This leads to the followingissues:It increases complexity of theimplementation.Growing a large array when itis full may be difficult orimpossible, whereas findingspace for a new linked listnode in a large, general memorypool may be easier.Adding elements to a dynamicarray will occasionally (whenit is full) unexpectedly takelinear (O(n)) instead ofconstant time (although it'sstill anamortized constant).Using a general memory poolleaves more memory for otherdata if the list is smallerthan expected or if many nodesare freed.For these reasons, thisapproach is mainly used forlanguages that do not supportdynamic memory allocation.These disadvantages are alsomitigated if the maximum sizeof the list is known at thetime the array is created.Language support[edit]Manyprogramming languages suchasLisp andScheme have singlylinked lists built in. In manyfunctional languages, theselists are constructed fromnodes, each called acons orcons cell. The cons has twofields: thecar, a reference tothe data for that node, and thecdr, a reference to the nextnode. Although cons cells canbe used to build other datastructures, this is theirprimary purpose.In languages that supportabstract data types ortemplates, linked list ADTs ortemplates are available forbuilding linked lists. In otherlanguages, linked lists aretypically built usingreferences together withrecords.Internal and external storage[edit]When constructing a linked list, one is faced with the choiceof whether to store the data ofthe list directly in the linkedlist nodes, calledinternalstorage, or merely to store areference to the data, calledexternal storage. Internalstorage has the advantage ofmaking access to the data moreefficient, requiring lessstorage overall, having betterlocality of reference, andsimplifying memory managementfor the list (its data isallocated and deallocated atthe same time as the list nodes).External storage, on the otherhand, has the advantage ofbeing more generic, in that thesame data structure and machinecode can be used for a linkedlist no matter what the size ofthe data is. It also makes iteasy to place the same data inmultiple linked lists. Althoughwith internal storage the samedata can be placed in multiplelists by including multiplenext references in the nodedata structure, it would thenbe necessary to create separateroutines to add or delete cellsbased on each field. It ispossible to create additionallinked lists of elements thatuse internal storage by usingexternal storage, and havingthe cells of the additionallinked lists store referencesto the nodes of the linked listcontaining the data.In general, if a set of datastructures needs to be includedin multiple linked lists,external storage is the bestapproach. If a set of datastructures need to be includedin only one linked list, theninternal storage is slightlybetter, unless a generic linkedlist package using externalstorage is available. Likewise,if different sets of data thatcan be stored in the same datastructure are to be included ina single linked list, theninternal storage would be fine.Another approach that can beused with some languagesinvolves having different datastructures, but all have theinitial fields, including thenext (andprev if double linkedlist) references in the samelocation. After definingseparate structures for eachtype of data, a genericstructure can be defined thatcontains the minimum amount ofdata shared by all the otherstructures and contained at thetop (beginning) of thestructures. Then genericroutines can be created thatuse the minimal structure toperform linked list typeoperations, but separateroutines can then handle thespecific data. This approach isoften used in message parsingroutines, where several typesof messages are received, butall start with the same set offields, usually including afield for message type. Thegeneric routines are used toadd new messages to a queuewhen they are received, andremove them from the queue inorder to process the message.The message type field is thenused to call the correctroutine to process the specifictype of message.Example of internal andexternal storage[edit]Suppose you wanted to create alinked list of families andtheir members. Using internalstorage, the structure mightlook like the following:recordmember { // member of afamilymember next;string firstName;integer age;}recordfamily { // the familyitselffamily next;string lastName;string address;member members// head of listof members of this family}To print a complete list offamilies and their membersusing internal storage, wecould write:aFamily := Families// start athead of families listwhile aFamily ≠null// loopthrough list of familiesprint information aboutfamilyaMember := aFamily.members// get head of list of thisfamily's memberswhile aMember ≠null// loopthrough list of membersprint informationabout memberaMember := aMember.nextaFamily := aFamily.nextUsing external storage, wewould create the followingstructures:recordnode { // generic linkstructurenode next;pointer data// generic pointerfor data at node}recordmember { // structure forfamily memberstring firstName;integer age}recordfamily { // structure forfamilystring lastName;string address;node members// head of list ofmembers of this family}To print a complete list offamilies and their membersusing external storage, wecould write:famNode := Families// start athead of families listwhile famNode ≠null// loopthrough list of familiesaFamily := (family)famNode.data// extract familyfrom nodeprint information aboutfamilymemNode := aFamily.members// get list of family memberswhile memNode ≠null// loopthrough list of membersaMember := (member)memNode.data// extract memberfrom nodeprint informationabout membermemNode := memNode.nextfamNode := famNode.nextNotice that when using externalstorage, an extra step isneeded to extract the recordfrom the node and cast it intothe proper data type. This isbecause both the list offamilies and the list ofmembers within the family arestored in two linked listsusing the same data structure (node), and this language doesnot have parametric types.As long as the number offamilies that a member canbelong to is known at compiletime, internal storage worksfine. If, however, a memberneeded to be included in anarbitrary number of families,with the specific number knownonly at run time, externalstorage would be necessary.Speeding up search[edit]Finding a specific element in alinked list, even if it issorted, normally requires O(n) time (linear search). This isone of the primarydisadvantages of linked listsover other data structures. Inaddition to the variantsdiscussed above, below are twosimple ways to improve searchtime.In an unordered list, onesimple heuristic for decreasingaverage search time is themove-to-front heuristic, whichsimply moves an element to thebeginning of the list once itis found. This scheme, handyfor creating simple caches,ensures that the most recentlyused items are also thequickest to find again.Another common approach is to "index" a linked list using amore efficient external datastructure. For example, one canbuild ared-black tree orhashtable whose elements arereferences to the linked listnodes. Multiple such indexescan be built on a single list.The disadvantage is that theseindexes may need to be updatedeach time a node is added orremoved (or at least, beforethat index is used again).Random access lists[edit]A random access list is a listwith support for fast randomaccess to read or modify anyelement in the list.[6] Onepossible implementation is askew binary random access listusing theskew binary numbersystem, which involves a listof trees with specialproperties; this allows worst-case constant time head/consoperations, and worst-caselogarithmic time random accessto an element by index.[6]Random access lists can beimplemented aspersistent datastructures.[6]Random access lists can beviewed as immutable linkedlists in that they likewisesupport the same O(1) head andtail operations.[6]A simple extension to randomaccess lists is themin-list, which provides an additionaloperation that yields theminimum element in the entirelist in constant time (without[clarification needed] mutationcomplexities).[6]Related data structures[edit]Bothstacks andqueues areoften implemented using linkedlists, and simply restrict thetype of operations which aresupported.Theskip list is a linked listaugmented with layers ofpointers for quickly jumpingover large numbers of elements,and then descending to the nextlayer. This process continuesdown to the bottom layer, whichis the actual list.A binary tree can be seen as atype of linked list where theelements are themselves linkedlists of the same nature. Theresult is that each node mayinclude a reference to thefirst node of one or two otherlinked lists, which, togetherwith their contents, form thesubtrees below that node.Anunrolled linked list is alinked list in which each nodecontains an array of datavalues. This leads to improvedcache performance, since morelist elements are contiguous inmemory, and reduced memoryoverhead, because less metadataneeds to be stored for eachelement of the list.A hash table may use linkedlists to store the chains ofitems that hash to the sameposition in the hash table.A heap shares some of theordering properties of a linkedlist, but is almost alwaysimplemented using an array.Instead of references from nodeto node, the next and previousdata indexes are calculatedusing the current data's index.A self-organizing listrearranges its nodes based onsome heuristic which reducessearch times for data retrievalby keeping commonly accessednodes at the head of the list.Notes[edit]^The amount of control data requiredfor a dynamic array is usually of theform, where is a per-array constant, is a per-dimensionconstant, and is the number ofdimensions. andare typically on the order of 10 bytes.Footnotes[edit]^Gerald Kruse.CS 240 Lecture Notes: Linked Lists Plus: Complexity Trade-offs. Juniata College. Spring 2008.^Day 1 Keynote - Bjarne Stroustrup:C++11 Style atGoingNative 2012 onchannel9.msdn.com from minute 45 orfoil 44^Number crunching: Why you shouldnever, ever, EVER use linked-list inyour code again atkjellkod.wordpress.com^Brodnik, Andrej; Carlsson, Svante;Sedgewick, Robert; Munro, JI; Demaine,ED (1999),Resizable Arrays inOptimal Time and Space (TechnicalReport CS-99-09), Department ofComputer Science, University ofWaterloo^Ford, William and Topp, WilliamDataStructures with C++ using STL SecondEdition (2002). Prentice-Hall.ISBN 0-13-085850-1, pp. 466-467^ abcdeC Okasaki, "Purely Functional Random-Access Lists"References[edit]This article includes alist of references, butits sources remainunclear because it hasinsufficientinline citations. Please help toimprove thisarticle byintroducing moreprecise citations.(March 2012)Juan, Angel (2006)."Ch20 –Data Structures; ID06- PROGRAMMING with JAVA (slide part of the book "BigJava", by CayS. Horstmann)" (PDF). p. 3"Definition of a linked list". National Institute of Standardsand Technology. 2004-08-16. Retrieved2004-12-14.Antonakos, James L.; Mansfield,Kenneth C., Jr. (1999).Practical Data Structures UsingC/C++. Prentice-Hall. pp. 165–190.ISBN 0-13-280843-9.Collins, William J. (2005) [2002].Data Structures and theJava Collections Framework. New York: McGraw Hill. pp. 239–303.ISBN 0-07-282379-8.Cormen, Thomas H.;Charles E. Leiserson; Ronald L. Rivest; Clifford Stein(2003).Introduction toAlgorithms. MIT Press. pp. 205–213 & 501–505.ISBN 0-262-03293-7.Cormen, Thomas H.; Charles E. Leiserson; Ronald L. Rivest; Clifford Stein(2001). "10.2: Linked lists".Introduction to Algorithms(2nd ed.). MIT Press. pp. 204–209.ISBN 0-262-03293-7.Green, Bert F. Jr. (1961). "Computer Languages for SymbolManipulation".IRE Transactions on HumanFactors in Electronics (2): 3–8. doi:10.1109/THFE2.1961.4503292.McCarthy, John (1960)."Recursive Functions ofSymbolic Expressions and TheirComputation by Machine, Part I". Communications of the ACM3(4): 184.doi:10.1145/367177.367199.Knuth, Donald (1997). "2.2.3-2.2.5".Fundamental Algorithms (3rd ed.). Addison-Wesley. pp. 254–298.ISBN 0-201-89683-4.Newell, Allen; Shaw, F. C. (1957). "Programming the LogicTheory Machine".Proceedings of the WesternJoint Computer Conference: 230–240.Parlante, Nick (2001)."Linked list basics". Stanford University. Retrieved2009-09-21.Sedgewick, Robert (1998).Algorithms in C. Addison Wesley. pp. 90–109.ISBN 0-201-31452-5.Shaffer, Clifford A. (1998).A Practical Introduction to DataStructures and AlgorithmAnalysis. New Jersey: PrenticeHall. pp. 77–102.ISBN 0-13-660911-2.Wilkes, Maurice Vincent(1964). "An Experiment with aSelf-compiling Compiler for aSimple List-Processing Language".Annual Review in AutomaticProgramming (Pergamon Press)4(1): 1.doi:10.1016/0066-4138(64)90013-8.Wilkes, Maurice Vincent(1964). "Lists and Why They areUseful".Proceeds of the ACMNational Conference,Philadelphia 1964(ACM) (P–64): F1–1.Shanmugasundaram, Kulesh (2005-04-04)."Linux Kernel LinkedList Explained". Retrieved2009-09-21.External links[edit]Description from theDictionary of Algorithms andData StructuresIntroduction to Linked Lists, Stanford University ComputerScience LibraryLinked List Problems, StanfordUniversity Computer ScienceLibraryOpen Data Structures - Chapter3 - Linked ListsPatent for the idea of havingnodes which are in severallinked lists simultaneously (note that this technique waswidely used for many decadesbefore the patent was granted)Data structuresTypesCollectionContainerAbstractAssociative arrayDouble-endedpriority queueDouble-ended queueListMapMultimapPriority queueQueueSetmultisetDisjointSetsStackArraysBit arrayCircular bufferDynamicarrayHash tableHashed array treeSparse arrayLinkedAssociation listLinked listSkiplistUnrolled linked listXORlinked listTreesB-treeBinary search treeAAAVLred-blackself-balancingsplayHeapbinarybinomialFibonacciR-treeR*R+HilbertTrieHash treeGraphsBinary decision diagramDirectedacyclic graphDirected acyclic wordgraphList of data structuresCategories: Linked listsData structuresNavigationMain pageContentsFeatured contentCurrent eventsRandom articleDonate toWikipediaWikimedia ShopInteractionHelpAbout WikipediaCommunity portalRecent changesContact pageToolsWhat links hereRelated changesUpload fileSpecial pagesPermanent linkPage informationWikidata itemCite this pagePrint/exportCreate a bookDownload as PDFPrintable versionLanguagesالعربيةCatalàČeštinaDanskDeutschEspañolفارسیFrançais한국어HrvatskiBahasa IndonesiaÍslenskaItalianoעבריתLatviešuLietuviųMagyarBahasa MelayuNederlands日本語Norsk bokmålPolskiPortuguêsРусскийSlovenščinaСрпски / srpskiSuomiSvenskaไทยTürkçeУкраїнська中文This page was last modified on 7January 2015 at 22:09.Text is available under theCreativeCommons Attribution-ShareAlike License;additional terms may apply. By usingthis site, you agree to theTerms ofUse andPrivacy Policy. Wikipedia® is aregistered trademark of theWikimediaFoundation, Inc., a non-profitorganization.Comparison of list datastructuresLinked listArrayDynamicarrayBalancedtreeRandomaccess listIndexingΘ(n)Θ(1)Θ(1)Θ(log n)Θ(log n)Insert/deleteat beginningΘ(1)N/AΘ(n)Θ(log n)Θ(1)Insert/deleteat endΘ(n) when lastelement is unknown;Θ(1) when lastelement is knownN/AΘ(1)amortizedΘ(logn)Θ(logn) updatingInsert/deletein middlesearch time +Θ(1)[1][2][3]N/AΘ(n)Θ(logn)Θ(logn) updatingWasted space(average)Θ(n)0Θ(n)[4]Θ(n)Θ(n)Wikimedia Commons hasmedia related toLinkedlists.vteArticleTalkReadEditView historyEdit linksPrivacy policyAbout WikipediaDisclaimersContact WikipediaDevelopersMobile viewCreate accountLog in

1. Insertions and deletions are difficult. Insertions and deletions can be done easily.
2. It needs movements of elements for insertion and deletion.
It does not need movement of nodes for insertion and deletion.
3. In it space is wasted.
In it space is not wasted.
4. It is more expensive. It is less expensive.
5. It requires less space as only information is stored. It requires more space as pointers are also stored along with information.
6. Its size is fixed. Its size is not fixed.
7. It can not be extended or reduced according to requirements. It can be extended or reduced according to requirements.
8. Same amount of time is required to access each element. Different amount of time is required to access each element.
9. Elements are stored in consecutive memory locations. Elements may or may not be stored in consecutive memory locations.
10. If have to go to a particular element then we can reach there directly. If we have to go to a particular node then we have to go through all those nodes that come before that node.

Similar Documents