Chinaunix首页 | 论坛 | 博客
  • 博客访问: 95417
  • 博文数量: 41
  • 博客积分: 866
  • 博客等级: 准尉
  • 技术积分: 282
  • 用 户 组: 普通用户
  • 注册时间: 2011-11-22 22:49
文章分类

全部博文(41)

文章存档

2011年(41)

我的朋友

分类: C/C++

2011-11-26 18:06:45

链表逆序,即将原先的链表 a->b->c->d, 变为 d->c->b->a。需要使用三个指针来进行操作。

 

Cpp代码
  1. public int* reverse(int* head) {   
  2.     int* front = head;   
  3.     int* back = null;   
  4.     int* temp;   
  5.        
  6.     while (front != null) {   
  7.         temp = font - > next;   
  8.         font -> next = back;   
  9.         back = font;   
  10.         font = temp;   
  11.     }   
  12.        
  13.     return back;   
  14. }   
  15.       
public int* reverse(int* head) { int* front = head; int* back = null; int* temp; while (front != null) { temp = font - > next; font -> next = back; back = font; font = temp; } return back; } 

C++代码:

#include
using namespace std;

class Node
{
public:
int data;
Node* next;
};

Node* ReverseList(Node *head)
{
if((head->next == NULL) || (head == NULL))
return head;

Node *temp1 = head;
Node *temp2;
Node *temp3 = temp1->next;
temp1->next = NULL;
while(temp3->next != NULL)
{
temp2 = temp3;
temp3 = temp3->next;
temp2->next = temp1;
temp1 = temp2;
}
temp3->next = temp1;
return temp3;
}

int main()
{
Node* head1 = new Node();
Node* head2 = new Node();
Node* head3 = new Node();
Node* head4 = new Node();
Node* head5 = new Node();
Node* head6 = new Node();
Node* head7 = new Node();

head1->data=1;
head2->data=2;
head3->data=3;
head4->data=4;
head5->data=5;
head6->data=6;
head7->data=7;

head1->next=head2;
head2->next=head3;
head3->next=head4;
head4->next=head5;
head5->next=head6;
head6->next=head7;
head7->next=NULL;

Node *temp = ReverseList(head1);

while(temp != NULL)
{
cout<data<<"\t";
temp = temp->next;
}
cout<
delete head1,head2,head3,head4,head5,head6,head7;
return 0;
}

阅读(712) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~