【题目7】逆转一个单链表

解题思路:网上有很多解决方案,这里介绍一种比较简单的,好理解的吧。

当前节点:cur = NULL;

上一个节点:last = NULL;

头节点: head

开始时: 4---->3----->2---->1

            -> head

头指针往前移动:

             4<---3---->2---->1

                   ->

                   head

            ->cur

            ->last

头指针往前移动:

               4<---3<----2---->1

                                ->

                              head

                    ->cur

                    ->last

 

 源代码: (在VC6下通过编译,执行OK)

 #include <stdio.h> #include <stdlib.h> struct Node { Node* next; int value; }; Node* ReverseLink(Node* head) { Node* cur = NULL; Node* last = NULL; while(head->next) { cur = head; head = head->next; cur->next = last; last = cur; } head->next = last; return head; } Node* InsertNode(Node* head,int value) { if(head == NULL) { head = (Node*)malloc(sizeof(Node)); if(head == NULL) printf("malloc failed."); else { head->next = NULL; head->value = value; } } else { Node* cur = (Node*)malloc(sizeof(Node)); if(cur == NULL) printf("malloc failed."); else { cur->next = head; head = cur; cur->value = value; } } return head; } Node* FreeLink(Node* head) { while(head->next) { Node* cur = head->next; free(head); head = cur; } return NULL; } void PrintLink(Node* head) { Node* p=head; while(p->next) { printf("%d ",p->value); p = p->next; } printf("%d/n",p->value); } int main() { Node* link =NULL; link = InsertNode(link,1); link = InsertNode(link,2); link = InsertNode(link,3); link = InsertNode(link,4); PrintLink(link); link = ReverseLink(link); PrintLink(link); FreeLink(link); return 0; }

你可能感兴趣的:(【题目7】逆转一个单链表)