Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

Pointerで連結リストの順序を逆転する

連結リストの要素の並びを逆転する

連結リストに要素を追加したあとにその並び順を逆転するコードは下記となります。

reversal.c
#include <stdio.h>
#include <stdlib.h>

//node declaration
struct node{
  int data;
  struct node *link;
};

//function declaration
void add(struct node **, int);
void reverse(struct node **);
void display(struct node *);

void main(){
  //declaration of pointer to point to linked list
  struct node *p;

  //set pointer to point to empty linked list
  p = NULL;

  //add nodes to linked list
  add(&p,3);
  add(&p,5);
  add(&p,7);
  add(&p,5);
  add(&p,9);

  //display nodes in linked list
  display(p);

  printf("Change order of linked list\n");

  //reverse order of linked list
  reverse(&p);

  //display nodes in linked list
  display(p);
}

//reverse nodes order in linked list
void reverse(struct node **q){
  struct node *current, *prev, *next;

  //set locator pointer to the first node
  current = *q;
  //set prev to null
  prev = NULL;

  //loop through linked list
  while(current!=NULL){
    //keep next node address
    next = current->link;
    //change link of current node to point to previous address
    current->link = prev;
    //keep current address
    prev = current;
    //go to next node
    current = next;    
  }

  //after looped through linked list, change p to point to the latest first node
  *q = prev;
}

//add node to the beginning of linked list
void add(struct node **q, int num){
  struct node *r;

  //create new node
  r = malloc(sizeof(struct node));
  //set value of new node
  r->data = num;
  //set link to point to address pointed by p
  r->link = *q;
  //set p to point to new node
  *q = r;
}

//display nodes in linked list
void display(struct node *q){
  while(q != NULL){
    printf("%d\n",q->data);
    q = q->link;
  }
}
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away