标签:
题目来源:http://www.lintcode.com/zh-cn/problem/reverse-linked-list/
可以accept的程序如下:
1 class Solution {
2 public:
3 /**
4 * @param head: The first node of linked list.
5 * @return: The new head of reversed linked list.
6 */
7 ListNode *reverse(ListNode *head) {
8 // write your code here
9 ListNode *temp1=NULL;
10 ListNode *temp2=head;
11 while(head!=NULL)
12 {
13 head=head->next;
14 temp2->next=temp1;
15 temp1=temp2;
16 temp2=head;
17 }
18 return temp1;
19 }
20 };
可以accept的程序2:
1 /**
2 * Definition of ListNode
3 *
4 * class ListNode {
5 * public:
6 * int val;
7 * ListNode *next;
8 *
9 * ListNode(int val) {
10 * this->val = val;
11 * this->next = NULL;
12 * }
13 * }
14 */
15 class Solution {
16 public:
17 /**
18 * @param head: The first node of linked list.
19 * @return: The new head of reversed linked list.
20 */
21 ListNode *reverse(ListNode *head) {
22 ListNode *prev = NULL;
23 while (head != NULL) {
24 ListNode *temp = head->next;
25 head->next = prev;
26 prev = head;
27 head = temp;
28 }
29 return prev;
30 }
31 };
完整的测试程序如下:
1 #include <iostream>
2 using namespace std;
3
4 class ListNode {
5 public:
6 int val;
7 ListNode *next;
8 ListNode(int val) {
9 this->val = val;
10 this->next = NULL;
11 }
12 };
13
14 class Solution {
15 public:
16 /**
17 * @param head: The first node of linked list.
18 * @return: The new head of reversed linked list.
19 */
20 ListNode *reverse(ListNode *head) {
21 // write your code here
22 ListNode *temp1=NULL;
23 ListNode *temp2=head;
24 while(head!=NULL)
25 {
26 head=head->next;
27 temp2->next=temp1;
28 temp1=temp2;
29 temp2=head;
30 }
31 return temp1;
32 }
33 };
34
35 int main()
36 {
37 Solution solu;
38 //动态创建链表
39 ListNode *head,*temp,*result;
40 head=new ListNode(10);
41 temp=head;
42 temp->next=new ListNode(20);
43 temp=temp->next;
44 temp->next=new ListNode(30);
45 temp=temp->next;
46 temp->next=NULL;
47 //输出翻转后的结果
48 result=solu.reverse(head);
49 temp=result;
50 cout<<temp->val<<" "<<temp->next->val<<" "<<temp->next->next->val<<endl;
51 }
标签:
原文地址:http://www.cnblogs.com/hslzju/p/5458825.html