Skip to content

Instantly share code, notes, and snippets.

@rpappalax
Last active August 15, 2016 06:13
Show Gist options
  • Save rpappalax/14b6a0172244cdbb769a41b20ef8f309 to your computer and use it in GitHub Desktop.
Save rpappalax/14b6a0172244cdbb769a41b20ef8f309 to your computer and use it in GitHub Desktop.
algorithms: list_ins_next statement outline
/*********************************************
* EXAMPLE
*********************************************
Below is an outline of steps for inserting a node into a singly
linked list using method statements.
*/
/* linked-list element structure */
typedef struct ListElmt_ {
void *data;
struct ListElmt_ *next;
} ListElmt;
/* linked list structure */
typedef struct List_ {
int size;
ListElmt *head;
ListElmt *tail;
} List;
// Initial List contains 2 nodes
List = *L;
+---------+------+ +---------+------+
| SJC | * → | → → | LAX | * |
+---------+------+ +---------+------+
// demo function
void link_ins_next(List *list, ListElmt *element, const void *data){
ListElmt *N;
// declare a (new) pointer var N (point to list nodes)
// allocate new node, let pointer var N point to it
N = (ListElmt *)malloc(sizeof(ListElmt));
+---------+------+
| NULL | * |
+---------+------+
// Copy the data str "SFO" into the airport field of N's referent
// We could also pass the data in as an input var (i.e. *data)
strcpy(N->Airport, "SFO");
+---------+------+
| SFO | * |
+---------+------+
// Change the link field of N's referent to point to the 2nd node of list L
+---------+------+
N: | SFO | * |
+---------+--↓---+
+---------+------+ +---------+------+
L: | SJC | * | | LAX | * |
+---------+------+ +---------+------+
N->Link = L->Link;
// Change the link field of the 1st node of list L to point to N's referent
+---------+------+
| SFO | * |
+---------+--↓---+
↗ ↓
↗ ↓
+---------+---↗--+ +---------+------+
| SJC | * | | LAX | * |
+---------+------+ +---------+------+
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment