方法一:迭代递推
- //带哨兵位
- void reverse1(LinkList* phead) {
- LinkList* pre = phead->next, * nex = NULL;
- phead->next = NULL;
- while (pre != NULL) {
- nex = pre->next;
- pre->next = phead->next;
- phead->next = pre;
- pre = nex;
- }
- }
- //不带哨兵位
- void reverse2(LinkList** phead) {
- LinkList* pre = NULL, * nex = NULL;
- while ((*phead) != NULL) {
- nex = (*phead)->next;
- (*phead)->next = pre;
- pre = (*phead);
- (*phead) = nex;
- }
- (*phead) = pre;
- }
方法二:遍历原链表,头插新链表(过于无脑)
- struct ListNode* newhead = NULL;
- struct ListNode* cur = head;
- while(cur!=NULL){
- struct ListNode* nextN = cur->next;
- cur->next = newhead;
- newhead = cur;
- cur = nextN;
- }
- return newhead;