DS\逆置带头节点单链表
本帖最后由 ~风介~ 于 2016-5-19 23:59 编辑/*
*简介:逆置带头结点单链表。
*方法:将原链表数据用尾插法生成新链表 。
*Powered by Niko!
*/
#include <stdio.h>
#include <stdlib.h>
#define OK 1
#define ERROR -1
typedef int ElemType;
typedef int Status;
typedef struct Node
{
ElemType data;
struct Node *next;
}linkedList; //此处需要加分号
Status printLinkedList(linkedList *head);
linkedList *createLinkedList();
linkedList *reverseLinkedList(linkedList *head);
Status printLinkedList(linkedList *head)
{
linkedList *p;
for (p=head->next; p!=NULL; p=p->next)
printf("%-3d", p->data);
printf("\n");
return OK;
}
//头插法
linkedList *createLinkedList()
{
int i = 0;
linkedList *head, *L = (linkedList*)malloc(sizeof(linkedList));
head = L;
L->next = NULL;
printf("please input integer<end with '86'>: \n");
scanf("%d", &i);
while (86 != i)
{
linkedList *p = (linkedList*)malloc(sizeof(linkedList));
p->data = i;
p->next = L->next; //把p指向L指向的那个节点 (开始时L指向NULL)。
L->next = p;
scanf("%d", &i);
}
return head;
}
linkedList *reverseLinkedList(linkedList *head)
{
printf("逆置后:\n");
//定义
int i = 0;
linkedList *newHead,*L = (linkedList*)malloc(sizeof(linkedList));
newHead = L;//插入过程中节点L不断往后移动
L->next = NULL;
for (head=head->next; head!=NULL; head=head->next)
{
linkedList *p = (linkedList *)malloc(sizeof(linkedList));
p->data = head->data;
p->next = L->next;
L->next = p;
L = p;
}
return newHead;
}
int main()
{
printLinkedList(reverseLinkedList(createLinkedList()));
return 0;
}
C++编程小组 这个必须要看看那啊
页:
[1]