Joel Coding Problem reverse_list

mohadang·2023년 4월 16일
0

Coding Problem

목록 보기
6/7
post-thumbnail
#include <stdio.h>

struct Node {
  struct Node* next;
  int data;  
};

void display(struct Node* node) {
  for (struct Node* cur = node; cur != NULL; cur = cur->next) {
    printf("%d -> ", cur->data);
  }
  printf("end\n");
}

struct Node* reverse_list(struct Node* node) {
  struct Node* prev = NULL;
  struct Node* cur = node;
  while (cur != NULL) {
    struct Node* back_next = cur->next;
    cur->next = prev;
    prev = cur;
    cur = back_next;
  }
  return prev;
}

#define LEN 7

int main() {
  int i;
  struct Node nodes[LEN] = {0, };
  for(i = 0; i + 1 < LEN; i++){
    nodes[i].next = &nodes[i+1];
    nodes[i].data = i + 1;
  }
  nodes[i].next = NULL;
  nodes[i].data = i + 1;

  display(nodes);
  struct Node* new_head = reverse_list(nodes);
  display(new_head);

  return 0;
}
profile
mohadang

0개의 댓글