样例
给出一个链表1->2->3->null,这个翻转后的链表为3->2->1->null
解题思路:
1.首先利用尾插法建立单链表。
2.定义preNode节点和curNode节点,然后利用while循环,定义tempNode节点用于存储preNode节点的下一个节点。具体看代码更易于理解。
时间复杂度O(N)
还有另外一种思路就是在建立链表的时候建立成双链表,这样简单很多,但是只限于题目不限制链表类型情况。
具体代码:
C++写法:
#include <iostream>
using namespace std;
typedef struct LinkNode {
int value;
LinkNode * next;
}LinkNode;
LinkNode * creatLink(int n){
LinkNode * node = NULL;
while (n!=0) {
LinkNode * tempNode = (struct LinkNode *)malloc(sizeof(struct LinkNode));
int tempValue ;
cin>>tempValue;
tempNode->value = tempValue;
tempNode->next = node;
node = tempNode;
n--;
}
return node;
}
LinkNode * reverseLink(LinkNode * node) {
LinkNode * curNode = node;
LinkNode * preNode = node->next;
curNode->next = NULL;
while (preNode != NULL) {
LinkNode * tempNode = preNode->next;
preNode->next = curNode;
curNode = preNode;
preNode = tempNode;
}
return curNode;
}
int main(int argc, const char * argv[]) {
// insert code here...
std::cout << "Hello, World!\n";
LinkNode * headNode = creatLink(5);
LinkNode * reverseHeadNode = reverseLink(headNode);
return 0;
}
Pyhton写法:
class ListNode():
def __init__(self):
self.val = 0
self.next = None
class Solution():
def reverseLink(self, head:ListNode) -> ListNode:
if head is None : return None
list = []
while head is not None:
list.append(head)
head = head.next
head = list.pop()
temp = head
while list:
temp.next = list.pop()
temp = temp.next
temp.next = None
return head
node3 = ListNode()
node3.val = 3
node3.next = None
node2 = ListNode()
node2.val = 2
node2.next = node3
node1 = ListNode()
node1.val = 1
node1.next = node2
s = Solution()
head = s.reverseLink(node1)
print(head)