题目描述
输入一个链表,反转链表后,输出新链表的表头。
方法一:
#include<stdio.h>
#include<malloc.h>
typedef struct Node {
int data;
struct Node *pnext;
} Node,*pnode;
pnode CreateNode() {
pnode phead=(pnode)malloc(sizeof(Node));
if(phead==NULL) {
printf("fail to allocate memory");
return false;
}
phead->pnext=NULL;
int n;
pnode ph=phead;
for(int i=0; i<5; i++) {
pnode p=(pnode)malloc(sizeof(Node));
if(p==NULL) {
printf("fail to allocate memory");
return false;
}
p->data=(i+2)*19;
phead->pnext=p;
p->pnext=NULL;
phead=phead->pnext;
}
return ph;
}
int list(pnode head) {
int count=0;
while(head->pnext!=NULL) {
printf("%d\t",head->pnext->data);
head=head->pnext;
count++;
}
return count;
}
void reverse1(pnode head,int count) {
int a[5]= {0};
for(int i=0; i<count,head->pnext!=NULL; i++) {
a[i]=head->pnext->data;
head=head->pnext;
}
for(int j=0,i=count-1; j<count; j++,i--)
printf("%d\t",a[i]);
}
int main() {
pnode p=CreateNode();
pnode p3=CreateNode();
int n=list(p);
printf("\n反转:\n");
reverse1(p,n);
printf("\n");
free(p);
return 0;
}
方法二:
class Solution {
public:
ListNode* ReverseList(ListNode* head) {
if(NULL==head|| NULL==head->next) return head;
ListNode* p;
ListNode* q;
ListNode* r;
p = head;
q = head->next;
head->next = NULL;
while(q) {
r = q->next;
q->next = p;
p = q;
q = r;
}
head=p;
return head;
}
};
思路:方法一:将单链表储存为数组,然后按照数组的索引逆序进行反转。比较浪费空间。时间复杂度:O(N)。空间复杂度:O(N)。此处不再赘述。
方法二:使用3个指针遍历链表,逐个连接点进行反转。首先将头结点链表方向改变,即head->next = NULL;之后用r存储q的next,此处不能直接将q连到头结点处,这样会使后续地址被丢弃,从而后续链表保存的数据也无法访问,所以设置一个临时指针。存储完q的next之后将q连到p的后面。如此进行循环,直到q为空。时间复杂度:O(N)。空间复杂度:O(1)
https://www.jianshu.com/p/84117123f709