/******************************************************************************
只是其中一种实现方式
*******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
struct DoubleListNode {
int val;
struct DoubleListNode *prev;
struct DoubleListNode *next;
};
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* init(int val){
struct ListNode* head = malloc(sizeof(struct ListNode));
head->next = NULL;
head->val = val;
return head;
}
void insert(struct ListNode* head, int val){
struct ListNode* p = head;
while(p->next){
p = p->next;
}
struct ListNode* node = malloc(sizeof(struct ListNode));
node->next = NULL;
node->val = val;
p->next = node;
}
struct DoubleListNode* initDouble(int val){
struct DoubleListNode*head = malloc(sizeof(struct DoubleListNode));
head->prev = NULL;
head->next = NULL;
head->val = val;
return head;
}
void insertDouble(struct DoubleListNode* head, int val){
if (head == NULL){
head = malloc(sizeof(struct DoubleListNode));
head->prev = NULL;
head->next = NULL;
head->val = val;
return;
}
struct DoubleListNode* p = head;
while(p->next){
p = p->next;
}
struct DoubleListNode* doubleNode= malloc(sizeof(struct DoubleListNode));
doubleNode->prev = p;
doubleNode->next = NULL;
doubleNode->val = val;
p->next = doubleNode;
}
void print(struct ListNode* head){
struct ListNode* p = head;
while(p){
printf("%d ", p->val);
p = p->next;
}
}
void printDNode(struct DoubleListNode* head){
struct DoubleListNode* p = head;
while(p){
printf("%d ", p->val);
p = p->next;
}
}
int main()
{
struct ListNode* head = init(1);
insert(head,2);
insert(head,3);
insert(head,3);
insert(head,2);
insert(head,1);
print(head);
printf("\n");
struct DoubleListNode* doubleHead = initDouble(head->val);
struct ListNode* p = head;
struct DoubleListNode* dp = doubleHead;
while(p->next){
p = p->next;
insertDouble(dp,p->val);
}
printDNode(doubleHead);
printf("\n");
struct DoubleListNode* dTail = doubleHead;
while(dTail->next){
dTail = dTail->next;
}
int ret = 0;
while(dp){
if (dp->val == dTail->val){
dp = dp->next;
dTail = dTail->prev;
if (dp == dTail){
ret = 1;
break;
}
}else{
break;
}
}
printf("%d\n",ret);
return 0;
}
C语言,回文链表判断,单链表转双链表
最新推荐文章于 2022-06-01 09:26:18 发布