定义单链表的结点
typedef struct ListNode{ int value; ListNode *next; }ListNode;
我们采用的单链表是带头结点的。
需要遍历一遍链表,在遍历过程中,把遍历的节点一次插入到头部。在这个过程之后,第一个节点成了最后节点,因此要特殊处理,改其后继为NULL。
void Inversion(ListNode* head) { if(head->next == NULL) return; //带头结点的单链表,当单链表为空时 if(head->next->next == NULL) return; //只有一个结点 ListNode* pre = head->next; ListNode* current = head->next->next; //或者 current = pre->next; while(current != NULL) { pre->next = current->next; current->next = head->next; head->next = current; current = pre->next; } }
测试代码:
#include <stdio.h> #include <stdlib.h> int main() { ListNode * head = (ListNode*)malloc(sizeof(ListNode)); if(NULL == head) printf("malloc failed!\n"); ListNode* tmp = head; for(int i=1; i<=10; i++) { tmp->next = (ListNode*)malloc(sizeof(ListNode)); tmp->next->value = i; tmp->next->next = NULL; tmp = tmp->next; } Inversion(head); tmp = head->next; while(1) { printf("tmp->value is %d\n", tmp->value); if(tmp->next == NULL) break; tmp = tmp->next; } return 0; }
参考:http://blog.csdn.net/kangroger/article/details/20237081
http://blog.csdn.net/cyuyanenen/article/details/51473900
http://blog.csdn.net/liujian20150808/article/details/50640979
时间: 2024-10-12 00:33:10