简体   繁体   中英

Single Linked List Reverse

I'm trying to learn linked lists. I am having a tiny bit of trouble. I've learnt some basic concepts. Such as reading in numbers in the list as shown here: My questions are:

  1. Can anyone give me some hints on how to improve this code? I know it's quite messy.
  2. If I were to reverse this linked list (keeping the addresses and content same) but manipulating the pointers.

How would I do so? I do NOT want the full solution, just some hints. If anyone can draw me any diagrams on how to reverse a linked list that would be appreciated.

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

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

int main (int argc, char *argv[]){

   struct node *pNew, *pHead, *pCurr;
   int i, dataEntered, numberOfNodes;
   printf("Please enter the amount of nodes: ");
   scanf("%d", &numberOfNodes);   

   for (i = 0; i < numberOfNodes; i++){
      printf("Enter data for node %d : ", numberOfNodes-i);
      scanf("%d", &dataEntered);     
      pNew = malloc (sizeof(struct node));
      pNew -> data = dataEntered;
      pNew -> next = pHead;
      pHead = pNew;   
   }

   pCurr = pHead;
   for (i = 0; i < numberOfNodes; i++){
      printf("Node %d has a data value of: %d\n", i, pCurr->data);
      pCurr = pCurr->next;

   }


   return 0;
}

Let me give you a bit code..

struct node *nex, *curr, *pre;
curr = phead;
pre = 0;
while(curr)
{
       nex = curr->next;
       curr->next = pre;
       pre = curr;
       curr = nex;
}
phead = pre;

对于链表反转,这非常简单,只需创建一个新的链表,然后将新节点放在链表的末尾(始终从第二个LList的头开始遍历,直到当前节点的下一个为null为止,然后将pNew放入当前-> next)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM