链表逆置C语言完整代码
2019-07-02 本文已影响0人
zhake
链表逆置C语言完整代码
#include<stdio.h>
typedef struct node {
int num;
struct node *next;
}Lnode;
Lnode *createlink(int n)
{
int num;
Lnode *head = NULL;
Lnode *pend = head;
while (n > 0)
{
scanf("%d", &num);
Lnode *pnew = (struct node*)malloc(sizeof(struct node));
pnew->num = num;
pnew->next = NULL; //新创建的指针的下一个位置还没有定
if (head == NULL)
{
head = pnew;
pend = pnew;
}
else
{
pend->next = pnew;
pend = pnew;
}
n--;
}
return head;
}
int isPalindrome(Lnode* head) {//O(n)、O(1)
Lnode* slow = head, *fast = head, *prev = NULL;
while (fast) {//find mid node
slow = slow->next;
fast = fast->next ? fast->next->next : fast->next;
}
while (slow) {//reverse
Lnode* ovn = slow->next;
slow->next = prev;
prev = slow;
slow = ovn;
}
while (head && prev) {//check
if (head->num != prev->num) {
return 0;
}
head = head->next;
prev = prev->next;
}
return 1;
}
void print(Lnode* L) {
Lnode* p = L;
while (p)
{
printf("%d", p->num);
p = p->next;
}
printf("\n");
}
int main() {
Lnode *L;
L = createlink(5);
print(L);
printf("\n");
printf("真假%d\n", isPalindrome(L));
print(L);
}