题目:
链表操作,
(1)单链表就地逆置,
(2)合并链表
- #include <cstdio>
- #include <stdlib.h>
- typedef struct node
- {
- struct node *next;
- int value;
- }LinkList;
- void CreateList(LinkList *L);
- void Reverse(LinkList *L);
- void Output(LinkList *L);
- int main()
- {
- LinkList *L=(LinkList*)malloc(sizeof(LinkList)); //L为空头结点
- L->next=NULL;
- CreateList(L);
- printf("Before reverse,the items are: \n");
- Output(L);
- Reverse(L);
- printf("After reverse,the items are: \n");
- Output(L);
- return 0;
- }
- void CreateList(LinkList *L) //头插法建立单链表
- {
- int value;
- LinkList *tail=L,*newNode=NULL; //tail为链表尾结点
- printf("Please input values:\n");
- while (scanf("%d",&value)!=EOF)
- {
- newNode=(LinkList*)malloc(sizeof(LinkList));
- newNode->value=value;
- newNode->next=NULL;
- tail->next=newNode;
- tail=newNode;
- }
- }
- void Reverse(LinkList *L) //把链表结点拆开,重新按尾插法建立单链表
- {
- LinkList*tail=L->next,*head=NULL,*s=NULL; //tail为链表尾部,head为断开的链表头结点,s为head后一个结点
- if (tail==NULL)
- {
- return;
- }
- head=tail->next;
- tail->next=NULL;
- while (head!=NULL)
- {
- s=head->next;
- head->next=tail;
- L->next=head;
- tail=head;
- head=s;
- }
- }
- void Output(LinkList *L)
- {
- LinkList *r=L->next;
- while (r!=NULL)
- {
- printf("%d ",r->value);
- r=r->next;
- }
- printf("\n");
- }
解释一下逆置算法:
还有一种方法:
从一本书上截了一张图
关键代码如下:
- LinkList *p=head,*q;
- head=NULL;
- while (p!=NULL)
- {
- q=p->next;
- p->next=head;
- head=p;
- p=q;
- }
给出完整代码:
- #include <cstdio>
- #include <stdlib.h>
- typedef struct node
- {
- struct node *next;
- int value;
- }LinkList;
- void CreateList(LinkList *L);
- void Reverse(LinkList *L);
- void Output(LinkList *L);
- int main()
- {
- LinkList *L=(LinkList*)malloc(sizeof(LinkList)); //L为空头结点
- L->next=NULL;
- CreateList(L);
- printf("Before reverse,the items are: \n");
- Output(L);
- Reverse(L);
- printf("After reverse,the items are: \n");
- Output(L);
- return 0;
- }
- void CreateList(LinkList *L) //头插法建立单链表
- {
- int value;
- LinkList *tail=L,*newNode=NULL; //tail为链表尾结点
- printf("Please input values:\n");
- while (scanf("%d",&value)!=EOF)
- {
- newNode=(LinkList*)malloc(sizeof(LinkList));
- newNode->value=value;
- newNode->next=NULL;
- tail->next=newNode;
- tail=newNode;
- }
- }
- void Reverse(LinkList *L) //把链表结点拆开,重新按尾插法建立单链表
- {
- LinkList*head=L->next,*p=NULL,*q=NULL; //tail为链表尾部,head为断开的链表头结点,s为head后一个结点
- if (head==NULL)
- {
- return;
- }
- p=head;
- head=NULL;
- while (p!=NULL)
- {
- q=p->next;
- p->next=head;
- head=p;
- if (q==NULL) //如果p为最后一个结点,则把头结点指向它
- {
- L->next=p;
- }
- p=q;
- }
- }
- void Output(LinkList *L)
- {
- LinkList *r=L->next;
- while (r!=NULL)
- {
- printf("%d ",r->value);
- r=r->next;
- }
- printf("\n");
- }