链表反转

来源:互联网 发布:大数据上市公司有几家 编辑:程序博客网 时间:2024/06/17 00:19

在知乎上看见浙大查重被查了这道题,写了一下。面试常见的一道题。

原链表:head->1->2->3->null

方法:遍历一次,头插法重新排列。

head->null

head->1->null

....

head->3->2->1->null

#include <iostream>#include <vector>#include <string>using namespace std;typedef struct ListNode {int val;ListNode *next;ListNode(int x) : val(x), next(NULL) {}}ListNode;ListNode *fun(ListNode *head){ListNode *cur = head->next;//原链表节点head->next = NULL;while (cur)//重新头插法{ListNode *behind = cur->next;ListNode *temp = cur;//temp和cur绑定 temp变了 cur也变了temp->next = head->next;head->next = temp;cur = behind;/*ListNode *behind = cur->next;cur->next = head->next;head->next = cur;cur = behind;*/}return head;}int main(){ListNode *head = new ListNode(0);ListNode *n1=new ListNode(1);ListNode *n2=new ListNode(2);ListNode *n3=new ListNode(3);head->next = n1; n1->next = n2; n2->next = n3;ListNode *hhh = fun(head);ListNode *h = hhh->next;while (h){cout << h->val << endl;h = h->next;}_getch();return 0;}

原创粉丝点击