如有以下的链表 1-->2-->3-->4-->NULL,指定逆转前2个元素变为:2-->1-->3-->4
实现的代码如下(C语言):
<span style="font-size:18px;">#include<stdio.h>
#include<malloc.h>
typedef struct Node
{
int data;
struct Node * next;
}Node;
Node * createLink() // 创建带头节点的单链表
{
Node *head,*p,*q;
p = (Node *)malloc(sizeof(Node));
p->data = -1;
head = p;
int x;
printf("请输入单链表的元素,0表示结束输入\n");
scanf("%d",&x);
while(x!=0)
{
q = (Node *)malloc(sizeof(Node));
q->data = x;
p->next = q;
q->next = NULL;
p = q;
scanf("%d",&x);
}
return head;
}
void printLink(Node * Link) //输出链表
{
Node * p = (Node *)malloc(sizeof(Node));
p = Link->next;
while(p!=NULL)
{
printf("%d ",p->data);
p = p->next;