一、不使用额外存储空间的逆序
LinkList ReverseLink(LinkList L) { LinkList *next; LinkList *prev = NULL; LinkList *head = L->next; while(head != NULL) { next = head->next; head->next = prev; prev = head; head = next; } L->next = prev return L; }
二、头插法逆序
LinkList ListReverse(LinkList L) { LinkList current,pnext,prev; if(L == NULL || L->next == NULL) return L; current = L->next; /* p1指向链表头节点的下一个节点 */ pnext = current->next; current->next = NULL; /* 断开链表 */ while(pnext) { prev = pnext->next; pnext->next = current; current = pnext; pnext = prev; printf("交换后:current = %d,next = %d \n",current->data,current->next->data); } L->next = current; /* 将链表头节点指向p1 */ return L; }
三、递归逆序
/*链表的逆序*/ Node* reverse_list(Node *plist, Node *&head) //这个函数的返回值并不是最终链表逆序后的链表头,而是尾, //它的头保存在head指针里,所以head用的是指针引用. { Node *pback = NULL; if(plist == NULL || plist->next == NULL) { head->next = plist; return plist; } else { pback = reverse_list(plist->next, head); pback->next = plist; return plist; } }
时间: 2024-10-20 19:39:05