Skip to content

Instantly share code, notes, and snippets.

@tamarous
Created October 17, 2016 12:37
Show Gist options
  • Select an option

  • Save tamarous/4077d7d32ce16b08af32eca1c3661de0 to your computer and use it in GitHub Desktop.

Select an option

Save tamarous/4077d7d32ce16b08af32eca1c3661de0 to your computer and use it in GitHub Desktop.
反转链表,链表不带头节点
#include <stdio.h>
#include <stdlib.h>
struct Node;
typedef struct Node * ptrToNode;
typedef ptrToNode List,Position;
struct Node
{
int element;
ptrToNode next;
};
List makeList()
{
int n,e;
printf("Please enter the number of elements in this list: ");
scanf("%d",&n);
ptrToNode head,p;
for(int i = 0;i < n;i++)
{
printf("Enter the %dth element: ",i+1);
scanf("%d",&e);
ptrToNode node = (ptrToNode)malloc(sizeof(struct Node));
if (i == 0)
{
p = node;
}
node->element = e;
head->next = node;
head = head->next;
}
return p;
}
List reverse(List l)
{
if (l == NULL && l->next == NULL)
return NULL;
ptrToNode head = l,next = NULL;
ptrToNode pre = NULL;
while (head != NULL)
{
next = head->next;
head->next = pre;
pre = head;
head = next;
}
return pre;
}
void printList(List l)
{
Position p = l;
while (p != NULL)
{
printf("%d ",p->element);
p = p->next;
}
printf("\n");
}
int main()
{
List l = makeList();
printList(l);
List nl = reverse(l);
printList(nl);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment