单链表逆置

来源:互联网 发布:图像矩阵有负值 编辑:程序博客网 时间:2024/05/18 03:50

将单链表进行逆置是比较基本的数据结构操作,分析过程省略。迭代的方式比较简单,采用链表插入的前插入法可以将链表逆置。

ListNode* reverse(ListNode *head){if (!head || !head->next)return head;ListNode node, *hd = &node; node.next = NULL;while (head){ListNode *tmp = head; head = head->next;tmp->next = hd->next; hd->next = tmp;}       return node.next;}

递归的方法

ListNode* reverse(ListNode *head){if (!head || !head->next)return head;ListNode* tmp = reverse(head->next);head->next->next = head; head->next = NULL;        return tmp;}



0 0
原创粉丝点击