赞
踩
反转一个单链表。链表为无头结点、单向、不循环。(由于涉及到结构体,所以写不了完整的测试代码,下面展示的代码为 LeetCode 中写的代码)(LeetCode链接)
//递归的函数 struct ListNode* func(struct ListNode* node){ if(node->next == NULL){ return node;//这里返回的节点就是最终逆置好了的链表的头结点 } //保留当前节点 struct ListNode* cur = node; node = node->next; struct ListNode* ret = func(node); node->next = cur; return ret; } struct ListNode* reverseList(struct ListNode* head){ //递归的方法 if(head == NULL||head->next == NULL){ return head; } struct ListNode* ret = func(head); head->next = NULL; return ret; //头插法 if(head == NULL||head->next ==NULL){ return head; } //重新创建一个头结点,用来头插入数据 struct ListNode list; list.next = NULL; struct ListNode* node = head; while(node){ struct ListNode* next = node->next; node->next = list.next; list.next = node; node = next; } return list.next; //三指针法 if(head == NULL||head->next ==NULL){ return head; } struct ListNode* p1 = head; struct ListNode* p2 = p1->next; struct ListNode* p3 = p2->next; //将原来的头结点指向NULL,就可将其作为尾结点 p1->next = NULL; while(p2){ //更新指针 p3 = p2->next; p2->next = p1; p1 = p2; p2 = p3; } return p1; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。