Segregate Odd and Even numbers in Linked List, segmentation fault - c

#include <stdio.h>
#include <stdlib.h>
//////////////////////////////////////////////////////////////////////////////////
typedef struct _listnode
{
int item;
struct _listnode *next;
} ListNode; // You should not change the definition of ListNode
typedef struct _linkedlist
{
int size;
ListNode *head;
} LinkedList; // You should not change the definition of LinkedList
//////////////////////// function prototypes /////////////////////////////////////
void moveOddItemsToBack(LinkedList *ll);
void printList(LinkedList *ll);
void removeAllItems(LinkedList *ll);
ListNode * findNode(LinkedList *ll, int index);
int insertNode(LinkedList *ll, int index, int value);
int removeNode(LinkedList *ll, int index);
void appendNode(LinkedList *ll, int item);
//////////////////////////// main() //////////////////////////////////////////////
int main()
{
LinkedList ll;
int c, i, j;
c = 1;
//Initialize the linked list 1 as an empty linked list
ll.head = NULL;
ll.size = 0;
printf("1: Insert an integer to the linked list:\n");
printf("2: Moves all odd integers to the back of the linked list:\n");
printf("0: Quit:\n");
while (c != 0)
{
printf("Please input your choice(1/2/0): ");
scanf("%d", &c);
switch (c)
{
case 1:
printf("Input an integer that you want to add to the linked list: ");
scanf("%d", &i);
j = insertNode(&ll, ll.size, i);
printf("The resulting Linked List is: ");
printList(&ll);
break;
case 2:
moveOddItemsToBack(&ll); // You need to code this function
printf("The resulting Linked List after moving odd integers to the back of the Linked List is: ");
printList(&ll);
removeAllItems(&ll);
break;
case 0:
removeAllItems(&ll);
break;
default:
printf("Choice unknown;\n");
break;
}
}
return 0;
}
//////////////////////////////////////////////////////////////////////////////////
void moveOddItemsToBack(LinkedList *ll)
{
ListNode *cur , *tail, *pre ;
/* Get tail ptr to the last node */
tail = ll->head ;
while (tail->next != NULL)
tail = tail->next ;
ListNode *newTail = tail ;
newTail = tail ;
/* Start traversing list and put all odd items to tail */
cur = ll->head ;
pre = cur ;
while (cur != tail){
if(cur->item % 2 != 0) { // <- Segmentation Fault!
pre->next = cur->next ;
newTail->next = cur ;
newTail->next->next = NULL ;
cur = pre->next ;
newTail = newTail->next ;
}
else {
pre = cur ;
cur = cur->next ;
}
}
}
void appendNode(LinkedList *ll , int item){
/* Insert Node to empty list */
ListNode *cur;
if (ll->head == NULL ) {
ll->head = malloc(sizeof(ListNode));
ll->head->item = item ;
ll->size++ ;
}
cur = ll->head ;
/* Append to non-empty */
if (ll->head != NULL ) {
while (cur->next != NULL) {
cur = cur->next ;
}
cur->next = malloc(sizeof(ListNode)) ;
cur->next->item = item ;
ll->size++ ;
}
}
//////////////////////////////////////////////////////////////////////////////////
void printList(LinkedList *ll){
ListNode *cur;
if (ll == NULL)
return;
cur = ll->head;
if (cur == NULL)
printf("Empty");
while (cur != NULL)
{
printf("%d ", cur->item);
cur = cur->next;
}
printf("\n");
}
void removeAllItems(LinkedList *ll)
{
ListNode *cur = ll->head;
ListNode *tmp;
while (cur != NULL){
tmp = cur->next;
free(cur);
cur = tmp;
}
ll->head = NULL;
ll->size = 0;
}
ListNode * findNode(LinkedList *ll, int index){
ListNode *temp;
if (ll == NULL || index < 0 || index >= ll->size)
return NULL;
temp = ll->head;
if (temp == NULL || index < 0)
return NULL;
while (index > 0){
temp = temp->next;
if (temp == NULL)
return NULL;
index--;
}
return temp;
}
int insertNode(LinkedList *ll, int index, int value){
ListNode *pre, *cur;
if (ll == NULL || index < 0 || index > ll->size + 1)
return -1;
// If empty list or inserting first node, need to update head pointer
if (ll->head == NULL || index == 0){
cur = ll->head;
ll->head = malloc(sizeof(ListNode));
ll->head->item = value;
ll->head->next = cur;
ll->size++;
return 0;
}
// Find the nodes before and at the target position
// Create a new node and reconnect the links
if ((pre = findNode(ll, index - 1)) != NULL){
cur = pre->next;
pre->next = malloc(sizeof(ListNode));
pre->next->item = value;
pre->next->next = cur;
ll->size++;
return 0;
}
return -1;
}
int removeNode(LinkedList *ll, int index){
ListNode *pre, *cur;
// Highest index we can remove is size-1
if (ll == NULL || index < 0 || index >= ll->size)
return -1;
// If removing first node, need to update head pointer
if (index == 0){
cur = ll->head->next;
free(ll->head);
ll->head = cur;
ll->size--;
return 0;
}
// Find the nodes before and after the target position
// Free the target node and reconnect the links
if ((pre = findNode(ll, index - 1)) != NULL){
if (pre->next == NULL)
return -1;
cur = pre->next;
pre->next = cur->next;
free(cur);
ll->size--;
return 0;
}
return -1;
}
The above is my code, I am trying to achieve
If the linked list is 2 3 4 7 15 18:
The resulting Linked List after moving odd integers to the back of the Linked List is: 2 4 18 3 7 15
by moving all Odd items to the back of the Linked list.
The function of interest would be void moveOddItemsToBack.
I am very confused, as when I use the example given above, 2,3,4,7,15,18. I am able to get the desired output.
However, using an example such as 1,3,4,7,15,18, where the first number is an odd number, i get a segmentation fault at this line.
while (cur != tail){
if(cur->item % 2 != 0) { // <- Segmentation Fault!
pre->next = cur->next ;
newTail->next = cur ;
newTail->next->next = NULL ;
cur = pre->next ;
newTail = newTail->next ;
}
Did i do something wrong?

You need special handling of the case cur == ll->head because in that case prev is not a legal previous element. Also you'll have to update ll->head
Like
if(cur->item % 2 != 0) { // <- Segmentation Fault!
{
if (cur == ll->head)
{
// Add new code here - perhaps something like
ll->head = cur->next;
prev = cur->next;
newTail->next = cur ;
newTail->next->next = NULL ;
cur = ll->head;
}
else
{
// Your current code
}

Related

Radix sort a linked list - linking the buckets

I'm trying to implement radix sort on a linked list based on an integer with the code below.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_DIGITS 10 // maximum number of digits in a key
// Structure for a node in the linked list
typedef struct node
{
int key; // the key to be sorted
char value[20]; // the value associated with the key
struct node *next; // pointer to the next node in the list
} Node;
// Function prototypes
void radixSort(Node **head);
Node *createNode(int key, const char *value);
Node *append(Node *head, int key, const char *value);
void printList(Node *head);
int main(void)
{
Node *head = NULL; // head of the linked list
// Create a linked list with some random keys and values
head = append(head, 456, "apple");
head = append(head, 345, "banana");
head = append(head, 123, "cherry");
head = append(head, 789, "date");
head = append(head, 231, "elderberry");
head = append(head, 567, "fig");
head = append(head, 876, "grape");
// Print the original list
printf("Original list:\n");
printList(head);
// Sort the list using radix sort
radixSort(&head);
// Print the sorted list
printf("Sorted list:\n");
printList(head);
return 0;
}
// Function to sort the linked list using radix sort
void radixSort(Node **head)
{
Node *bucket[10]; // array of buckets
Node *curr; // pointer to the current node
Node *tail[10]; // array of tails for each bucket
int i, j, k;
int factor; // factor to sort on
int digits[MAX_DIGITS]; // array to store the digits of the keys
// Initialize the buckets and tails
for (i = 0; i < 10; i++)
{
bucket[i] = NULL;
tail[i] = NULL;
}
// Find the maximum number of digits in the keys
int maxDigits = 0;
curr = *head;
while (curr != NULL)
{
int key = curr->key;
int numDigits = 0;
while (key > 0)
{
numDigits++;
key /= 10;
}
if (numDigits > maxDigits)
{
maxDigits = numDigits;
}
curr = curr->next;
}
// Loop through each digit, starting with the least significant digit
for (factor = 1; maxDigits > 0; factor *= 10, maxDigits--)
{
// Extract the digits of the keys
curr = *head;
while (curr != NULL)
{
digits[curr->key / factor % 10]++;
curr = curr->next;
}
// Cumulative sum of the digits
for (i = 1; i < 10; i++)
{
digits[i] += digits[i - 1];
}
// Sort the nodes into the appropriate buckets
curr = *head;
while (curr != NULL)
{
int digit = curr->key / factor % 10;
if (bucket[digit] == NULL)
{
bucket[digit] = curr;
tail[digit] = curr;
}
else
{
tail[digit]->next = curr;
tail[digit] = curr;
}
curr = curr->next;
}
// Rebuild the list in sorted order
*head = NULL;
for (i = 9; i >= 0; i--)
{
//printf("%dA\n",i);
if (bucket[i] != NULL)
{
//printf("%dB\n",i);
if (*head == NULL)
{
*head = bucket[i];
// printf("%dC\n",i);
}
else
{
//printf("%dD\n",i);
tail[9 - i]->next = bucket[i];
//printf("%dF\n",i);
}
// tail[9 - i] = tail[i];
}
else{
// printf("%dE\n",i);
}
//printf("here\n");
}
}
}
// Function to create a new node with the given key and value
Node *createNode(int key, const char *value)
{
Node *node = (Node*) malloc(sizeof(Node));
node->key = key;
strcpy(node->value, value);
node->next = NULL;
return node;
}
// Function to append a new node with the given key and value to the end of the list
Node *append(Node *head, int key, const char *value)
{
Node *newNode = createNode(key, value);
Node *curr = head;
if (head == NULL)
{
return newNode;
}
while (curr->next != NULL)
{
curr = curr->next;
}
curr->next = newNode;
return head;
}
// Function to print the linked list
void printList(Node *head)
{
Node *curr = head;
while (curr != NULL)
{
printf("(%d, %s) ", curr->key, curr->value);
curr = curr->next;
}
printf("\n");
}
The segmentation fault occurs when tail[9 - i]->next = bucket[i]; is executed.
I added printf statements (turned them into comment blocks) to trace where the error is. Can someone please help me figure out a way to get this to work?
There are a few issues:
tail[9 - i]->next = bucket[i]; sets the wrong pointer. There is no reason why it should be 9 - i. It could even be that tail[9 - i] is NULL. So this leads to indefined behaviour. Instead you should keep track of what the current tail node is in the list that is being built. You could use curr for that purpose. Let it start (before the loop) with curr = NULL and then when you find a non-null bucket, end that process by setting curr = tail[i]. When a bucket is found when the *head is no longer NULL, make the link with curr->next = bucket[i].
The new list is not terminated with a NULL pointer. When the above point is implemented, continue after the loop with curr->next = NULL.
In the next iteration of the factor loop, both digits and buckets need to be reset. You could do this with a loop or with memset.
Here is the corrected factor loop code -- comments indicate where corrections were made:
for (factor = 1; maxDigits > 0; factor *= 10, maxDigits--)
{
memset(digits, 0, sizeof(digits)); // reset!
memset(bucket, 0, sizeof(bucket)); // reset!
curr = *head;
while (curr != NULL)
{
digits[curr->key / factor % 10]++;
curr = curr->next;
}
for (i = 1; i < 10; i++)
{
digits[i] += digits[i - 1];
}
curr = *head;
while (curr != NULL)
{
int digit = curr->key / factor % 10;
if (bucket[digit] == NULL)
{
bucket[digit] = curr;
tail[digit] = curr;
}
else
{
tail[digit]->next = curr;
tail[digit] = curr;
}
curr = curr->next;
}
*head = NULL;
curr = NULL; // <-- track the current tail of the newly built list
for (i = 9; i >= 0; i--)
{
if (bucket[i] != NULL)
{
if (*head == NULL)
{
*head = bucket[i];
}
else
{
curr->next = bucket[i]; // Append bucket after the current tail
}
curr = tail[i]; // The tail is now at the end of this bucket
}
}
curr->next = NULL; // Terminate the list properly
}

How to delete all smallest numbers in doubly linked list

I have a function that deletes the smallest node in a doubly-linked list. But if there are more than one same-valued integers, the function deletes the first one. I need to do, that function deletes all the smallest values.
I think I need to make a loop, to check all the values in the linked list and delete them if they are == to the smallest one.
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
struct node *prev;
int number;
struct node *next;
} node;
node *createList(struct node *head, int n);
node *addToEmpty(node *head, int data);
node *addAtEnd(node *head, int data);
node *deleteSmallest(node *head, int n);
void cleanUp(node *head);
int main()
{
node *head = NULL;
node *ptr;
int n;
printf("Enter number of the nodes: ");
scanf("%d", &n);
head = createList(head, n);
printf("\nN: %d\n\n", n);
ptr = head;
while(ptr != NULL)
{
printf("NUMBER:%d ADDRESS:%p PREVADD:%p NEXTADD:%p\n", ptr->number, ptr, ptr->prev, ptr->next);
ptr = ptr->next;
}
head = deleteSmallest(head, n);
printf("\n\n");
ptr = head;
while(ptr != NULL)
{
printf("NUMBER:%d ADDRESS:%p PREVADD:%p NEXTADD:%p\n", ptr->number, ptr, ptr->prev, ptr->next);
ptr = ptr->next;
}
// Free all the pointers
cleanUp(head);
return 0;
}
node *createList(struct node *head, int n)
{
int data;
if(n <= 0)
return head;
printf("Enter number of the 1 node: ");
scanf("%d", &data);
head = addToEmpty(head, data);
for(int i = 1; i < n; ++i)
{
printf("Enter number of the %d node: ", i + 1);
scanf("%d", &data);
head = addAtEnd(head, data);
}
return head;
}
node *addToEmpty(node *head, int data)
{
node *temp = malloc(sizeof(node));
temp->prev = NULL;
temp->next = NULL;
temp->number = data;
head = temp;
return head;
}
node *addAtEnd(node *head, int data)
{
node *temp, *tp;
temp = malloc(sizeof(node));
temp->prev = NULL;
temp->next = NULL;
temp->number = data;
tp = head;
while (tp->next != NULL)
tp = tp->next;
tp->next = temp;
temp->prev = tp;
return head;
}
node *deleteSmallest(node *head, int n)
{
node *smallest, *temp, *temporaryHead;
int position = 1;
temporaryHead = head;
smallest = head;
// Finding which node has the smallest int
for(int i = 1; temporaryHead != NULL; ++i)
{
temp = temporaryHead->next;
if(smallest->number > temporaryHead->number)
{
smallest = temporaryHead;
position = i;
}
temporaryHead = temp;
}
temporaryHead = NULL;
temp = head;
// If node is in the middle
if(position > 1 && position < n)
{
while (position > 1) {
temp = temp->next;
--position;
}
temporaryHead = temp->prev;
temporaryHead->next = temp->next;
temp->next->prev = temporaryHead;
free(temp);
temp = NULL;
}else if(position == 1) // If node is the first element
{
head = head->next;
free(head->prev);
head->prev = NULL;
}else // If node is the last element
{
while(temp->next != NULL)
temp = temp->next;
temporaryHead = temp->prev;
temporaryHead->next = NULL;
free(temp);
temp = NULL;
}
return head;
}
void cleanUp(node *head)
{
node *next;
while(head != NULL)
{
next = head->next;
free(head);
head = next;
}
}
I think I need to make a loop, to check all the values in the linked list and delete them if they are == to the smallest one.
I didn't quite understand the logic of your current function (particularly, the n argument).
Here is a function that will allow just one element to be removed or all matching smallest elements. If there is only one it is a single scan pass. If there are more, it is just two scan passes:
// deleteSmallAll -- delete all nodes that are the smallest
node *
deleteSmallAll(node *head,int allflg)
// allflg -- 1=delete all, 0=delete first
{
node *small = head;
int smcount = 0;
int smnum = 0;
node *cur = head;
// skip over the first element (and assume it is the smallest)
if (cur != NULL) {
cur = cur->next;
smcount = 1;
smnum = small->number;
}
// find the smallest
for (; cur != NULL; cur = cur->next) {
int curnum = cur->number;
// got a smaller element
if (curnum < smnum) {
smcount = 1;
small = cur;
smnum = curnum;
continue;
}
// keep count of duplicate small numbers
if (curnum == smnum) {
if (allflg)
smcount += 1;
continue;
}
}
// start with the _first_ smallest node we found
cur = small;
// remove a single smallest and loop if more to do
while (cur != NULL) {
node *next = cur->next;
node *prev = cur->prev;
// unlink it
if (prev != NULL)
prev->next = next;
else
head = next;
// unlink it
if (next != NULL)
next->prev = prev;
// NOTE: no tail pointer
#if 0
else
tail = prev;
#endif
// release the node
free(cur);
// bug out if no more of that match
if (--smcount <= 0)
break;
// find the next in the list that is the same match
for (cur = next; cur != NULL; cur = cur->next) {
if (cur->number == smnum)
break;
}
}
return head;
}
UPDATE:
Hopefully, you've gotten an answer for your basic question.
But, as others pointed out, what's the point to have a doubly linked list if you only traverse it in the forward direction?
Below is an updated version. It uses a separate list struct and passes a pointer to that instead of passing in head and always returning the updated value.
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
typedef struct node {
struct node *prev;
int number;
struct node *next;
} node;
typedef struct {
node *head;
node *tail;
} list;
int
getnum(const char *prompt)
{
char buf[100];
int data = 0;
// debug hook for input from redirected file (e.g. ./myprogram < input.txt)
struct termios tio;
int fileflg = tcgetattr(fileno(stdin),&tio) < 0;
while (1) {
printf("%s: ",prompt);
fflush(stdout);
if (fgets(buf,sizeof(buf),stdin) == NULL) {
printf("getnum: premature EOF\n");
if (fileflg)
exit(1);
}
// echo the file input
if (fileflg)
fputs(buf,stdout);
if (sscanf(buf,"%d",&data) == 1)
break;
}
return data;
}
void
addAtEnd(list *lst, int data)
{
node *temp;
temp = malloc(sizeof(node));
temp->number = data;
if (lst->head == NULL)
lst->head = temp;
node *tail = lst->tail;
if (tail != NULL) {
temp->next = tail->next;
tail->next = temp;
temp->prev = tail;
}
else
temp->prev = NULL;
lst->tail = temp;
temp->next = NULL;
}
void
createList(list *lst, int n)
{
int data;
char msg[100];
for (int i = 0; i < n; ++i) {
sprintf(msg,"Enter number of the %d node", i + 1);
data = getnum(msg);
addAtEnd(lst, data);
}
}
// deleteSmallAll -- delete all nodes that are the smallest
void
deleteSmallAll(list *lst,int allflg)
// allflg -- 1=delete all, 0=delete first
{
node *small = lst->head;
int smcount = 0;
int smnum = 0;
node *cur = lst->head;
// skip over the first element (and assume it is the smallest)
if (cur != NULL) {
smcount = 1;
smnum = small->number;
cur = cur->next;
}
// find the smallest
for (; cur != NULL; cur = cur->next) {
int curnum = cur->number;
// got a smaller element
if (curnum < smnum) {
smcount = 1;
small = cur;
smnum = curnum;
continue;
}
// keep count of duplicate small numbers
if (curnum == smnum) {
if (allflg)
smcount += 1;
continue;
}
}
// start with the _first_ smallest node we found
cur = small;
// remove a single smallest and loop if more to do
while (cur != NULL) {
node *next = cur->next;
node *prev = cur->prev;
// unlink it
if (prev != NULL)
prev->next = next;
else
lst->head = next;
// unlink it
if (next != NULL)
next->prev = prev;
else
lst->tail = prev;
// release the node
free(cur);
// bug out if no more of that match
if (--smcount <= 0)
break;
// find the next in the list that is the same match
for (cur = next; cur != NULL; cur = cur->next) {
if (cur->number == smnum)
break;
}
}
}
void
cleanUp(list *lst)
{
node *next;
for (node *cur = lst->head; cur != NULL; cur = next) {
next = cur->next;
free(cur);
}
lst->head = NULL;
lst->tail = NULL;
}
void
print_fwd(list *lst,const char *msg)
{
node *ptr = lst->head;
printf("\n%s:\n",msg);
for (; ptr != NULL; ptr = ptr->next)
printf("NUMBER:%d ADDRESS:%p PREVADD:%p NEXTADD:%p\n",
ptr->number, ptr, ptr->prev, ptr->next);
}
void
print_bwd(list *lst,const char *msg)
{
node *ptr = lst->tail;
printf("\n%s:\n",msg);
for (; ptr != NULL; ptr = ptr->prev)
printf("NUMBER:%d ADDRESS:%p PREVADD:%p NEXTADD:%p\n",
ptr->number, ptr, ptr->prev, ptr->next);
}
int
main(void)
{
list lstx = { NULL, NULL };
list *lst = &lstx;
node *ptr;
int n;
n = getnum("Enter number of the nodes");
createList(lst, n);
printf("\nN: %d\n", n);
print_fwd(lst,"orig/fwd");
print_bwd(lst,"orig/bwd");
deleteSmallAll(lst, 0);
print_fwd(lst,"after1/fwd");
print_bwd(lst,"after1/bwd");
deleteSmallAll(lst, 1);
print_fwd(lst,"afterN/fwd");
print_bwd(lst,"afterN/bwd");
// Free all the pointers
cleanUp(lst);
return 0;
}
Here is the sample input:
6
2
6
2
7
8
2
Here is the sample output:
Enter number of the nodes: 6
Enter number of the 1 node: 2
Enter number of the 2 node: 6
Enter number of the 3 node: 2
Enter number of the 4 node: 7
Enter number of the 5 node: 8
Enter number of the 6 node: 2
N: 6
orig/fwd:
NUMBER:2 ADDRESS:0x11a4280 PREVADD:(nil) NEXTADD:0x11a42a0
NUMBER:6 ADDRESS:0x11a42a0 PREVADD:0x11a4280 NEXTADD:0x11a42c0
NUMBER:2 ADDRESS:0x11a42c0 PREVADD:0x11a42a0 NEXTADD:0x11a42e0
NUMBER:7 ADDRESS:0x11a42e0 PREVADD:0x11a42c0 NEXTADD:0x11a4300
NUMBER:8 ADDRESS:0x11a4300 PREVADD:0x11a42e0 NEXTADD:0x11a4320
NUMBER:2 ADDRESS:0x11a4320 PREVADD:0x11a4300 NEXTADD:(nil)
orig/bwd:
NUMBER:2 ADDRESS:0x11a4320 PREVADD:0x11a4300 NEXTADD:(nil)
NUMBER:8 ADDRESS:0x11a4300 PREVADD:0x11a42e0 NEXTADD:0x11a4320
NUMBER:7 ADDRESS:0x11a42e0 PREVADD:0x11a42c0 NEXTADD:0x11a4300
NUMBER:2 ADDRESS:0x11a42c0 PREVADD:0x11a42a0 NEXTADD:0x11a42e0
NUMBER:6 ADDRESS:0x11a42a0 PREVADD:0x11a4280 NEXTADD:0x11a42c0
NUMBER:2 ADDRESS:0x11a4280 PREVADD:(nil) NEXTADD:0x11a42a0
after1/fwd:
NUMBER:6 ADDRESS:0x11a42a0 PREVADD:(nil) NEXTADD:0x11a42c0
NUMBER:2 ADDRESS:0x11a42c0 PREVADD:0x11a42a0 NEXTADD:0x11a42e0
NUMBER:7 ADDRESS:0x11a42e0 PREVADD:0x11a42c0 NEXTADD:0x11a4300
NUMBER:8 ADDRESS:0x11a4300 PREVADD:0x11a42e0 NEXTADD:0x11a4320
NUMBER:2 ADDRESS:0x11a4320 PREVADD:0x11a4300 NEXTADD:(nil)
after1/bwd:
NUMBER:2 ADDRESS:0x11a4320 PREVADD:0x11a4300 NEXTADD:(nil)
NUMBER:8 ADDRESS:0x11a4300 PREVADD:0x11a42e0 NEXTADD:0x11a4320
NUMBER:7 ADDRESS:0x11a42e0 PREVADD:0x11a42c0 NEXTADD:0x11a4300
NUMBER:2 ADDRESS:0x11a42c0 PREVADD:0x11a42a0 NEXTADD:0x11a42e0
NUMBER:6 ADDRESS:0x11a42a0 PREVADD:(nil) NEXTADD:0x11a42c0
afterN/fwd:
NUMBER:6 ADDRESS:0x11a42a0 PREVADD:(nil) NEXTADD:0x11a42e0
NUMBER:7 ADDRESS:0x11a42e0 PREVADD:0x11a42a0 NEXTADD:0x11a4300
NUMBER:8 ADDRESS:0x11a4300 PREVADD:0x11a42e0 NEXTADD:(nil)
afterN/bwd:
NUMBER:8 ADDRESS:0x11a4300 PREVADD:0x11a42e0 NEXTADD:(nil)
NUMBER:7 ADDRESS:0x11a42e0 PREVADD:0x11a42a0 NEXTADD:0x11a4300
NUMBER:6 ADDRESS:0x11a42a0 PREVADD:(nil) NEXTADD:0x11a42e0
I would split the logic into parts:
A function to find the least value (an integer) in a list
A function to delete nodes from a list that have a given value
Use the above two functions to implement deleteSmallest
Here is how that could look:
int getSmallestValue(node *head) {
int smallest = head == NULL ? 0 : head->number;
while (head != NULL) {
if (head->number < smallest) {
smallest = head->number;
}
head = head->next;
}
return smallest;
}
node* deleteValue(node *head, int n) {
node* temp, *current;
while (head != NULL && head->number == n) {
temp = head;
head = head->next;
free(temp);
}
head->prev = NULL;
current = head->next;
while (current != NULL) {
temp = current;
current = current->next;
if (temp->number == n) {
temp->prev->next = current;
if (current != NULL) {
current->prev = temp->prev;
}
free(temp);
}
}
return head;
}
node *deleteSmallest(node *head, int n) {
return deleteValues(head, getSmallestValue(head));
}
If you were concerned about performance, instead of addAtEnd(), you might have addToFront(). This would reduce the asymptotic time from O(n^2) to O(n) to input the numbers.
If you must delete-minimum again and again, a linked-list is not really a good fit. As you have observed, all the input must be traversed if one wants to find the minimum, which takes O(n) each time. In this case, a binary heap would allow O(log n) delete-minimum. It does this by heapify, in which the heap is created by sifting down in O(n), and maintaining the heap property of each int is less than or equal to the int's children.
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
#include <errno.h>
static void int_to_string(const int *i, char (*const a)[12])
{ sprintf(*a, "%d", *i); }
#define HEAP_NAME int
#define HEAP_TYPE int
#define HEAP_TO_STRING
#include "heap.h"
int main(int argc, char **argv) {
struct int_heap ints = int_heap();
size_t n = 0;
int success = EXIT_SUCCESS;
(void)argc; /* Don't use. */
while(*++argv) { /* Get command line arguments. */
long argl;
char *end;
int *a;
argl = strtol(*argv, &end, 0); /* Convert to `long`. */
if(argl < INT_MIN || argl > INT_MAX || end == *argv || *end != '\0')
{ if(!errno) errno = ERANGE; goto catch; }
if(!(a = int_heap_buffer(&ints, n + 1))) goto catch;
a[n++] = (int)argl;
}
int_heap_append(&ints, n); /* Heapifies, O(n), <Floyd, 1964, Treesort>. */
while(ints.as_array.size) printf("pop: %d, remainder: %s\n",
int_heap_pop(&ints), int_heap_to_string(&ints));
printf("empty\n");
goto finally;
catch:
success = EXIT_FAILURE;
perror("count");
finally:
int_heap_(&ints);
return success;
}
I have used my implementation of a binary heap, which I've tried to make pretty standard. This is close to what heapsort does.

error signal(SIGABRT) raised in C program

Couldn't understand why my program is producing an error signal.
#include<stdio.h>
#include<stdlib.h>
struct Node{
int data;
struct Node *next;
};
int MAX_SIZE = 1;
char stack[1];
int top = -1;
int isempty() {
if(top == -1)return 1;
else return 0;
}
int isfull() {
if(top == 0)return 1;
else return 0;
}
int pop() {
int data;
if(!isempty()) {
data = stack[top];
top = top - 1;
return data;
} else {
printf("Could not retrieve data, Stack is empty.\n");
}
}
void push(int data) {
if(!isfull()) {
top = top + 1;
stack[top] = data;
} else {
printf("Could not insert data, Stack is full.\n");
}
}
struct Node* newNode(int d){
struct Node *temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = d;
temp->next = NULL;
return temp;
}
struct Node* reverse(struct Node* head){
//reverses the linked list and returns the pointer pointing to the first node of the reversed linked list.
struct Node *prev = NULL, *curr = head;
while (curr) {
struct Node* temp = curr->next;
curr->next = prev;
prev = curr;
curr = temp;
free(temp);
}
head = prev;
return head;
}
struct Node* addition(struct Node* first, struct Node* second){
struct Node *rev1, *rev2;
struct Node *res = NULL, *revres = NULL;
struct Node *temp, *prev = NULL;
int carry = 0, sum;
rev1 = reverse(first);
rev2 = reverse(second);
while (rev1 != NULL || rev2 != NULL) {
sum = carry + (rev1 ? rev1->data : 0) + (rev2 ? rev2->data : 0);
carry = (sum >= 1000) ? 1 : 0;
sum = sum % 1000;
temp = newNode(sum);
if (res == NULL)
res = temp;
else
prev->next = temp;
prev = temp;
if (rev1)
rev1 = rev1->next;
if (rev2)
rev2 = rev2->next;
}
if (carry > 0){
struct Node *new = newNode(carry);
temp->next = new;
free(new);
}
revres = reverse(res);
while (revres->data == 0 && revres->next) {
struct Node* temp = revres;
revres = revres->next;
free(temp);
}
return revres;
}
int length_reversal(struct Node** head_ref){
// reverses the given linkedlist in-place and also returns the number of nodes in the list.
struct Node* prev = NULL;
struct Node* current = *head_ref;
struct Node* next;
int len = 0;
while (current != NULL) {
len++;
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*head_ref = prev;
return len;
}
void addData(struct Node** head_ref, int new_data){
struct Node* new_node = newNode(new_data);
new_node->next = (*head_ref);
(*head_ref) = new_node;
free(new_node);
}
struct Node* make_empty_list(int size){
struct Node* head = NULL;
while (size--)
addData(&head, 0);
return head;
}
struct Node* multiplication(struct Node* first, struct Node* second){
int m = length_reversal(&first), n = length_reversal(&second);
struct Node* result = make_empty_list(m + n + 1);
struct Node *second_ptr = second, *result_ptr1 = result, *result_ptr2, *first_ptr;
while (second_ptr) {
int carry = 0;
result_ptr2 = result_ptr1;
first_ptr = first;
while (first_ptr) {
int mul = first_ptr->data * second_ptr->data + carry;
result_ptr2->data += mul % 1000;
carry = (mul / 1000) + (result_ptr2->data / 1000);
result_ptr2->data = result_ptr2->data % 1000;
first_ptr = first_ptr->next;
result_ptr2 = result_ptr2->next;
}
if (carry > 0) {
result_ptr2->data += carry;
}
result_ptr1 = result_ptr1->next;
second_ptr = second_ptr->next;
}
length_reversal(&result);
length_reversal(&first);
length_reversal(&second);
while (result->data == 0 && result->next) {
struct Node* temp = result;
result = result->next;
free(temp);
}
return result;
}
struct Node* input(FILE* fp){
char ch;
int i = 0;
struct Node *result = NULL, *first= NULL;
struct Node *it1 = NULL, *it2 = NULL, *it3 = NULL;
char str[3];
while(EOF != (ch=fgetc(fp)) && ch != '\n'){
if(ch == '=')return it1;
else if(ch == '0'||ch == '1'||ch == '2'||ch == '3'||ch == '4'||ch == '5'||
ch == '6'||ch == '7'||ch == '8'||ch == '9'){
if(i==3){printf("invalid input\n"); return NULL;}
str[i] = ch;
i++;
}
else if(ch == '+'){
push(ch);
}
else if(ch == '*'){
push(ch);
}
else if(ch == '$'){
it3 = newNode(atoi(str));
i = 0;
if(!first){
if(!it1)it1 = it3;
else it2 = it3;
}
else{
first->next = it3;
first = NULL;
}
if(!isempty()){
char c = pop();
if(c == '+'){result = addition(it1, it2); it1 = result; it2 = NULL;}
if(c == '*'){result = multiplication(it1, it2); it1 = result; it2 = NULL;}
}
}
else if(ch == ','){
if(first != NULL){
it3 = newNode(atoi(str));
first->next = it3;
first = first->next;
i=0;
}
else{
if(!it1){
first = newNode(atoi(str));
it1 = first;
i=0;
}
else{
first = newNode(atoi(str));
it2 = first;
i=0;
}
}
}
else if(ch == ' ') continue;
else {
printf("Invalid input");
return NULL;
}
}
return it1;
}
void output(FILE *fout, struct Node* list) {
struct Node *temp;
for (temp = list; temp->next != NULL; temp = temp->next)
fprintf (fout, "%03d,", temp->data);
fprintf(fout, "%03d$", temp->data);
fprintf (fout, "\n");
}
int main(){
FILE *fp;
fp = fopen("input_txt.txt", "r");
char c;
while(EOF != (c=getc(fp)) && c != '='){
ungetc(c, fp);
struct Node* res = input(fp);
if(res){
output(stdout, res);
}
}
return 0;
}
I have tried using a debugger to understand the problem, but no luck there.
The problem was described as
"""You will represent an arbitrarily large unsigned integer I by a singly linked list of its DIGITs d1 ,
d2 , ... , dm , where d1 is the least significant DIGIT of I and dm is the most significant DIGIT of I.
Assume that the DIGITs are from a number system with base 1,00010. Implement each DIGIT as a C
unsigned int with DIGIT values in [0, 999].
a) Write C functions to perform the arithmetic operations addition and multiplication of large
unsigned integers.
b) Write a C function to input a large unsigned integer from stdin as comma separated DIGITs
in decimal, ordered on decreasing significance and terminated by a $
c) Write a C function to output a large unsigned integer to stdout in the format used for input,
showing each DIGIT as 3 decimal digits.
d) Write a C main() which will repeatedly accept (from stdin) and evaluate, large integer infix
expressions on large unsigned integer constants using the operators “+” (addition) and “*”
(multiplication). An expression is terminated by “=”. On encountering an “=”, the value of
the expression is to be printed to stdout. Evaluate expressions from left to right. The main() loop
should terminate when it receives an empty expression (terminated by =)."""
This was my assignment question for which the deadline was over a week ago and I couldn't figure out the problem with my code.
For example, the 2 line input
111,041,411,111,011$ + 222,222$ * 003$ =
results in the output
333,124,233,999,699$

Removing Node from LinkedList

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
typedef struct _listnode
{
int item;
struct _listnode *next;
} ListNode;
int removeNode(ListNode **ptrHead, int index);
void printList(ListNode *head);
ListNode * findNode(ListNode *head, int index);
int main()
{
ListNode *head = NULL, *temp=NULL;
int i = 0;
int index = 0;
while (1)
{
printf("Enter a integer: ");
scanf("%d", &i);
if (i == -1)
break;
if (head == NULL)
{
head = malloc(sizeof(ListNode));
temp = head;
}
else{
temp->next = malloc(sizeof(ListNode));
temp = temp->next;
}
temp->item = i;
}
removeNode(&head, index);
return 0;
}
void printList(ListNode *head)
{
int i = 0;
if (head == NULL)
return;
while (head != NULL)
{
printf("%d ", head->item);
head = head->next;
}
printf("\n");
}
ListNode * findNode(ListNode *head, int index)
{
if (head == NULL || index < 0)
return NULL;
while (index > 0){
head = head->next;
if (head == NULL)
return NULL;
index--;
}
return head;
}
int removeNode(ListNode **ptrHead, int index)
{
ListNode *pre, *cur,*temp;
if (index >= 0)
{
printf("Enter index to remove: ");
scanf("%d", &index);
if ((pre = findNode(*ptrHead, index - 1)) != NULL)
{
cur = pre->next;
temp = cur;
pre->next = cur->next;
free(temp);
printList(*ptrHead);
}
}
return -1;
}
I successfully revamp my code and now I am able to remove the node and display out, but the whole program just crash after my printList function. It does not go back to remove node and I cant continue removing other indexes.
Output:
Enter a value: 2
Enter a value: 4
Enter a value: 6
Enter a value: 8
Enter a value: -1
Enter index to remove: 2
Current list: 2 4 8
Enter index to remove: 0
Current list: 4 8
Enter index to remove: -1
when you enter index = 0, the inner if block of removenode function will not be executed as the findnode functin returns NULL. But in your output for index = 0 you got node 2 removed. How did u get that?
removeNode(head, index); should be removeNode(&head, index);
And printList(ptrHead); should be printList(*ptrHead); (in removeNode) I have the feeling this piece of code goes crazy that's why your app is not responding anymore.
What compiler do you use? It should have warned you.
In your updated code:
You still do not set next to NULL.
You never increment index when you fill list.
You do not check if scanf() succeeds.
There is no need to use pointer to pointer in removeNode(), you can use:
int removeNode(ListNode *ptrHead, int index);
You have added removeNode() in printList() which is really out of place.
You do not have any free function for the list.
...
Original answer to original code:
Missing header file.
Miss match between function signatures in declaration and definition.
You never set next to NULL.
You do not free list before exit.
...
Code with some comments:
/* MISSING: <stdio.h> */
#include <stdlib.h>
typedef struct _listnode
{
int item;
struct _listnode *next;
} ListNode;
/* Signature miss-match */
int removeNode(ListNode **ptrHead, int index);
void printList(ListNode *head);
ListNode *findNode(ListNode *head, int index);
int main()
{
ListNode *head = NULL, *temp=NULL;
int i = 0;
int index = 0;
while (i != -1)
{
printf("Enter a integer: ");
scanf("%d", &i);
/* If -1 entered, -1 will be added to list. */
if (head == NULL)
{
head = malloc(sizeof(ListNode));
temp = head;
}
else{
temp->next = malloc(sizeof(ListNode));
temp = temp->next;
}
temp->item = i;
/* temp->next never set to NULL */
}
/* Miss match between function signature and call. */
removeNode(head, index);
/* No freeing of list before exit. */
return 0;
}
void printList(ListNode *head)
{
/* Redundant check of head != NULL */
if (head == NULL)
return;
while (head != NULL)
{
printf("%d", head->item);
head = head->next;
}
}
ListNode *findNode(ListNode *head, int index)
{
if (head == NULL || index < 0)
return NULL;
while (index > 0){
head = head->next;
if (head == NULL)
return NULL;
index--;
}
return head;
}
/* Why pass index as argument when it is not used? */
int removeNode(ListNode **ptrHead, int index)
{
ListNode *pre, *cur,*temp;
printf("Enter index to remove: ");
scanf("%d", &index);
/* Here you should check < 0, not != -1.
What if user enters -9999 ? */
if (index != -1)
{
if ((pre = findNode(*ptrHead, index - 1)) != NULL)
{
cur = pre->next;
temp = cur;
pre->next = cur->next;
free(temp);
/* Bad return statement, should be int */
return;
}
/* You only print list if none was removed. */
/* Miss match between function signature and call. */
printList(ptrHead);
}
return -1;
}

Sorting a linked list in C

I'm trying to sort a linked list by finding the largest value, deleting it from its position, and then inserting it at the top of the list.
The difficulty I'm running into is the actual deleting and inserting at the top. The issue seems to be in the if condition in the while loop contained within the sortList function, but I'm not sure how to fix it.
Any help would be appreciated.
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int num;
struct node *next;
} Node, *NodePtr;
void printList(NodePtr np);
NodePtr makeList(void);
NodePtr makeNode(int n);
NodePtr sortList(NodePtr list);
int main(void) {
NodePtr list;
printf("Enter numbers for the list (0 to end)\n");
list = makeList();
printList(list);
list = sortList(list);
printList(list);
return 0;
}
NodePtr makeList(void) {
NodePtr makeNode(int), np, top, last;
int n;
top = NULL;
if(scanf("%d", &n) != 1)n = 0;
while(n != 0) {
np = makeNode(n);
if(top == NULL)top = np;
else last->next = np;
last = np;
if(scanf("%d", &n)!=1)n=0;
}
return top;
}
void printList(NodePtr np) {
while(np != NULL) {
printf("%d\n", np->num);
np = np->next;
}
}
NodePtr makeNode(int n) {
NodePtr np = (NodePtr)malloc(sizeof(Node));
np->num = n;
np->next = NULL;
return np;
}
NodePtr sortList(NodePtr list) {
NodePtr top = list;
NodePtr curr = NULL;
NodePtr largest;
NodePtr prev;
prev = NULL;
curr = top;
largest = top;
while(curr != NULL) {
prev = curr;
if(curr->num > largest->num) {
largest = curr;
prev->next = curr->next;
largest->next = top;
}
curr = curr->next;
}
if(prev == NULL) {
largest->next = top;
return largest;
}
return largest;
}
There is issues in the sortList function.
This function only put some large nodes in the beginning of the list. It is not soting all the list. you can you a sort algorithm to sort the file : quicksort/ bubblesort/...
i put a code doing a sort in the end of this answer.
here is a code doing the sort of the list :
//it is replacing largest node with first one then doing the same operation with sublist (list-first element)
NodePtr sortList(NodePtr list)
{
//
if(list == null || list->next == null)
return list; // the list is sorted.
//replace largest node with the first :
//1- find largest node :
NodePtr curr, largest,largestPrev;
curr = list;
largest = list;
prev = list;
largestPrev = list;
while(curr != NULL) {
if(curr->num > largest->num) {
largestPrev = prev;
largest = curr;
}
prev = curr;
curr = curr->next;
}
//largest node is in largest.
//2- switching firt node and largest node :
NodePtr tmp;
if(largest != list)
{
largestPrev->next = list;
tmp = list->next;
list->next = largest->next;
largest->next = tmp;
}
// now largest is the first node of the list.
// calling the function again with the sub list :
// list minus its first node :
largest->next = sortList(largest->next);
return largest;
}
Here is my attempt to sort a singly linked list using QuickSort algorithm. If you know n then run time will be O(n log n). Check if this helps.
#include "malloc.h"
typedef struct node {
struct node *next;
int val;
} node;
bool insert_node(struct node **head, int val)
{
struct node *elem;
elem = (struct node *)malloc(sizeof(struct node));
if (!elem)
return false;
elem->val = val;
elem->next = *head;
*head = elem;
return true;
}
int get_lval(struct node *head, int l)
{
while(head && l) {
head = head->next;
l--;
}
if (head != NULL)
return head->val;
else
return -1;
}
void swap(struct node *head, int i, int j)
{
struct node *tmp = head;
int tmpival;
int tmpjval;
int ti = i;
while(tmp && i) {
i--;
tmp = tmp->next;
}
tmpival = tmp->val;
tmp = head;
while(tmp && j) {
j--;
tmp = tmp->next;
}
tmpjval = tmp->val;
tmp->val = tmpival;
tmp = head;
i = ti;
while(tmp && i) {
i--;
tmp = tmp->next;
}
tmp->val = tmpjval;
}
struct node *Quick_Sort_List(struct node *head, int l, int r)
{
int i, j;
int jval;
int pivot;
i = l + 1;
if (l + 1 < r) {
pivot = get_lval(head, l);
printf("Pivot = %d\n", pivot);
for (j = l + 1; j <= r; j++) {
jval = get_lval(head, j);
if (jval < pivot && jval != -1) {
swap(head, i, j);
i++;
}
}
swap(head, i - 1, l);
Quick_Sort_List(head, l, i);
Quick_Sort_List(head, i, r);
}
return head;
}
struct node *Sort_linkedlist(struct node *head)
{
struct node *tmp = head;
// Using Quick sort.
int n = 0;
while (tmp) {
n++;
tmp = tmp->next;
}
printf("n = %d\n", n);
head = Quick_Sort_List(head, 0, n);
return head;
}
void print_list(struct node *head)
{
while(head) {
printf("%d->", head->val);
head = head->next;
}
printf("\n");
}
int _tmain(int argc, _TCHAR* argv[])
{
struct node *head = NULL;
struct node *shead = NULL;
insert_node(&head, 10);
insert_node(&head, 12);
insert_node(&head, 9);
insert_node(&head, 11);
insert_node(&head, 7);
insert_node(&head, 1);
insert_node(&head, 3);
insert_node(&head, 8);
insert_node(&head, 5);
insert_node(&head, 2);
insert_node(&head, 4);
insert_node(&head, 6);
print_list(head);
shead = Sort_linkedlist(head);
print_list(shead);
return 0;
}
By writing to largest->next you overwrote curr->next. So you end up restarting from the top all the time.
Make sure that:
the list remains consistent
your list iterator remains consistent
But overall, your code seems to be heavily broken, I believe there might be a couple other errors in your sorting logic.
The following are some of the problems which exist in your sorting logic:
You are setting the prev pointer to curr in the beginning of the loop itself which is incorrect. By doing this, you are making the current pointer and the previous node pointer as same which makes it impossible to delete the node.
You should assign the largest pointer also to top whereby it facilitates the possibility of setting the largest->next to real top node.
The code can modified like below (Just a pointer, you need to check for other issues yourself):
while(curr != NULL)
{
if(curr->num > largest->num)
{
largest = curr;
prev->next = curr->next;
largest->next = top;
top = largest;
}
prev = curr;
curr = curr->next;
}
// Program to sort a single linked list in ascending order
// (without exchanging data in the nodes)
/**************************************************************************
There are two methods of sorting presented here(At a time,we can use any of
these two functions to sort our single linked list.) -
1. Function 'void Sort()' - This function uses selection sort method(I
think).
In this function,a node whose data is the smallest in the list is made
as 'head' node(i.e. starting node of the list) by scanning the whole list
once.Then from the remaining list,again a node with the smallest data is
found out whose address is kept in the 'next' field of previous node(head
node).This process continues to sort the whole list.
2. Function 'void Sort_method2()' - This function uses insertion sort
method(I think).
In this function,starting from second node in the list, all previous node
data(starting from 'head' node) are compared with current reference node
(which is initially second node in the list).If 'data' field of current
reference node is smaller than that of any of its previous nodes,then
suitable changes in the 'next' field of corresponding nodes are made.If
data in the current reference node is smaller than that in the 'head' node,
then the current reference node is made as 'head' node.
*********************************************************************/
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *head,*head1;
void Create_node(int data);
void display();
void Sort();
void Sort_method2();
void main()
{
int choice,d;
clrscr();
while(1)
{
printf("\n 1.Create new node");
printf("\n 2.Sort in ascending order");
printf("\n 3.Exit");
printf("\nEnter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1: printf("\nEnter data :");
scanf("%d",&d);
Create_node(d);
break;
case 2: Sort(); // At a time,we can use any of these two
//Sort_method2(); // functions to sort our single linked list.
break;
case 3: exit(0);
default:exit(0);
}
} // end of while(1)
} // end of main()
//--------------------------------------------
void Create_node(int d)
{
struct node *newnode,*temp;
newnode = (struct node *)malloc(sizeof(struct node));
newnode -> data = d;
newnode -> next = NULL;
if(head == NULL)
head = newnode;
else
{
temp = head;
while(temp -> next != NULL)
temp = temp -> next;
temp -> next = newnode;
} // end of 'else'
} // end of 'Create_node(int d)'
//---------------------------------------------
void display() // Print linked list contents
{
struct node *temp;
printf("\nList contents are :\n");
temp = head;
while(temp != NULL)
{
printf(" Data = %d Address = %u\n",temp->data,temp);
temp = temp->next;
}
printf("\n");
}
//--------------------------------------------
void Sort()
{
struct node *t,*t1,*t2,*t3;
t1 = head;
head1 = head;
if(head == NULL)
printf("\nThe linked list is empty!");
else
{
while( (t2 = t1 -> next) != NULL)
{
while(t2 != NULL)
{
t3 = t2 -> next;
if( t1 -> data > t2 -> data)
{
t2 -> next = t1;
for(t = t1; t -> next != t2;t = t -> next);
t -> next = t3;
t1 = t2; // t1 = Node with smaller data
t2 = t3; // t2 = Node to be compared with t1
} // end of 'if'
else
{
// t1 = t1; // That is,no change in t1.
t2 = t3;
}
} // end of ' while(t2 != NULL)'
if(head == head1) // We want this action only for first pass of
{ // outer while() loop.Only initially, head = head1.
head = t1;
head1 = t1 -> next;
} // end of 'if(head == head1)'
else
{
for(t = head;t -> next != head1; t = t -> next);
t -> next = t1;
head1 = t1 -> next;
} // end of 'else'
t1 = t1 -> next;
} // end of 'while( (t2 = t1 -> next) != NULL)'
display(); // Display the list.
} // end of 'else' of 'if(head == NULL)'
} // end of 'Sort()'
//--------------------------------------------
void Sort_method2()
{
struct node *t,*t1,*t2,*tt;
if(head == NULL)
printf("\nThe linked list is empty!");
else
{
t1 = head -> next;
while(t1 != NULL) // This is i-loop(outer loop).
{
t2 = t1 -> next;
for(t = head; t != t1; t = t -> next) // This is j-loop(inner loop).
{
if(t1->data < t->data)
{
t1 -> next = t;
for(tt=head; tt->next != t1; tt=tt->next); //end of for loop in 'if'
tt -> next = t2;
if(t == head)
head = t1; // There is only one statement in this 'if'.
else // i.e.,'if(t != head)'
{
for(tt=head; tt->next != t; tt=tt->next);
tt -> next = t1;
}
break;
} // end of 'if'
} // end of outer 'for' loop
t1 = t2;
} // end of 'while'
display(); // Display the list.
} // end of 'else' of 'if(head == NULL)'
} // end of 'Sort_method2()'

Resources