题目
反转一个单链表。
例子
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
要求
/**
- Definition for singly-linked list.
- struct ListNode {
-
int val;
-
struct ListNode *next;
- };
/
struct ListNode reverseList(struct ListNode* head){
}
代码
#include<stdio.h>
#include<stdlib.h>
#define len sizeof(struct ListNode)
struct ListNode
{
int val;
struct ListNode *next;
};
int n = 0;
struct ListNode *creat() //指针函数
{
struct ListNode *head, *p1, *p2;
p1=p2=( struct ListNode*) malloc(len);
char c;
scanf("%d",&p1->val);
head=NULL;
n=0;
while(p1->val!=0) //编号为0,输入结束
{
n=n+1;
if(n==1)
head=p1; //第一个,置头指针
else
p2->next=p1; //新开结点接上
p2=p1;
p1=(struct ListNode*)malloc(len);
scanf("%d",&p1->val);
} //p1指向新开结点,p2指向最后结点
p2->next=NULL;
return(head);
}
void print(struct ListNode *head)
{
struct ListNode *p = head;
while(p != NULL)
{
printf("%d ",p->val);
p=p->next;
}
printf("\n");
}
struct ListNode* reverseList(struct ListNode* head)
{
if(head == NULL||head->next == NULL)
return head;
else
{
struct ListNode *newhead = reverseList(head->next);
head ->next->next = head;
head->next = NULL;
return newhead;
}
}
int main()
{
int i,x,y;
struct ListNode *head;
head = creat();
head = reverseList(head);
print(head);
return 0;
}
注意输入的时候尾巴上要加一个0
比如输入 1 5 9 6 3 5 0
输出5 3 6 9 5 1