倒置链表,一道被出烂的题目,完整实现如下:
# include <stdio.h> # include <malloc.h> typedef struct LNode{ int data; struct LNode *next; }LNode,*LinkList; /** * 采用数组a[]来初始化链表,数组的长度为length;head指向了头节点。 */ LinkList CreatList(int a[],int length) { LinkList head = (LinkList)malloc(sizeof(LNode)); head->next = NULL; int index; LinkList temp; for (index = 0; index < length; index ++) { temp = (LinkList)malloc(sizeof(LNode)); temp->data = a[index]; temp->next = head->next; head->next = temp; } return head; } /* * 打印链表,head指向了头节点,不要打印头节点的内容 */ void PrintList(LinkList head) { LinkList current = head->next; //带头结点 while (current != NULL) { printf("%d ",current->data); current = current->next; } printf("/n"); } int main() { int a[] = {1,2,3,4,5}; LinkList list = CreatList(a,5); PrintList(list); Reverse(list); printf("After reverse/n"); PrintList(list); }
运行结果:
5 4 3 2 1
After reverse
1 2 3 4 5