Link list is used when relating other elements which in turn becomes part of network. So node comes in picture. Elements of linked lists are called nodes.
##
# next => just next left or right: not necessarily right to the current node
class Node:
def __init__(self):
self.data = None
self.next = None
class LinkedList:
def __init__(self):
self.node = None
def add_node(self, data):
new_node = Node()
new_node.data = data
new_node.next = self.node
self.node = new_node
def show_data(self):
current_node = self.node
while current_node is not None:
print current_node.data
current_node = current_node.next
l = LinkedList()
for x in range(1,5):
l.add_node(x)
# The list can be traversed only once
l.show_data()
'''
def print_list(l):
while l.node is not None:
print l.node.data
l.node = l.node.next
'''
#! /usr/bin/env python
class node:
def __init__(self):
self.data = None # contains the data
self.next = None # contains the reference to the next node
class linked_list:
def __init__(self):
self.cur_node = None
def add_node(self, data):
new_node = node() # create a new node
new_node.data = data
new_node.next = self.cur_node # link the new node to the 'previous' node.
self.cur_node = new_node # set the current node to the new one.
def list_print(self):
node = self.cur_node # cant point to ll!
while node:
print node.data
node = node.next
ll = linked_list()
ll.add_node(1)
ll.add_node(2)
ll.add_node(3)
ll.list_print()
:#: Link list in C:
#include<stdlib.h>
#include<stdio.h>
struct list_el {
int val;
struct list_el * next;
};
typedef struct list_el item;
void main() {
item * curr, * head;
int i;
head = NULL;
for(i=1;i<=10;i++) {
curr = (item *)malloc(sizeof(item));
curr->val = i;
curr->next = head;
head = curr;
}
curr = head;
while(curr) {
printf("%d\n", curr->val);
curr = curr->next ;
}
}
No comments:
Post a Comment