在知乎上看见浙大查重被查了这道题,写了一下。面试常见的一道题。
原链表: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;
}
ListNode *fun(ListNode *head)//用一个pre和behind来指针反转
{
ListNode *cur = head->next;
//head->next = NULL;
ListNode *pre = NULL;
while (cur)
{
ListNode *behind = cur->next;
cur->next = pre;
pre = cur;
cur = behind;
if (cur == NULL)
{
head->next =pre;
break;
}
}
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;
}