无法交换单个链接列表中的节点

时间:2019-10-29 16:40:38

标签: c pointers nodes

我目前正在尝试创建一种算法,该算法创建单个链接列表,并按升序(用户输入n和数字)对其进行排序。

我可以很好地创建列表,但是当我尝试交换2个节点的值时,它会给出出口,分段错误。 我强烈感觉到这与为节点动态分配的内存有关,但是对编程而言这是非常新的,所以我可以使用任何帮助来定位故障

#include <stdio.h>
#include <stdlib.h>
struct node {
    int val;
    struct node *next;
  }*node_st;
void createlist (int n) {
  struct node *fnNode, *temp;
  int i, num;
  node_st = (struct node *)malloc(sizeof(struct node));

  if (node_st == NULL) {
    printf("Memory allocation fault!");
    exit(0);
  }
  else {
    printf("Input data for node 1:");
    scanf("%d",&num);
    node_st->val =num;
    node_st->next = NULL;
    temp = node_st;

    for (i=2;i<=n;i++) {
      fnNode = (struct node *)malloc(sizeof(struct node));
       if (fnNode == NULL) {
         printf("Memory allocation fault!");
         break;
       }
       else {
         printf("input data for node %d : ", i);
         scanf("%d",&num);

         fnNode->val = num;
         fnNode->next = NULL;
         temp->next = fnNode;
         temp = temp->next;
       }
    } 
  }
  }
void showlist() {
  struct node *temp;
    if (node_st == NULL) {
      printf("List is empty..");

  }
  else {
  temp = node_st;
  while (temp != NULL) {
    printf("Value = %d \n",temp->val);
    temp = temp->next;
  }
  }
  }
void sort(int n) {
  struct node *temp;
  struct node *temp2;
    if (node_st == NULL) {
      printf("List is empty..");

  }
  else {
  temp = node_st;
  temp2 = temp->next;
  while (temp != NULL) {
    if (temp->val > temp2->val) {
    printf("test!!!");
    temp = temp2;
    temp2 = temp->next;
    }


  }
  }
  }

int main(void) {
  int n,a,x,y,z;
  printf("Input amount of nodes you want");
  scanf("%d",&n);
  createlist(n);
  printf("Data entered: \n");
  showlist();
  sort(n);

  return 0;
} 

aplogize in advance for the messy code, again im new and havent cleaned it up 100%.

0 个答案:

没有答案